0

如何在以下查询中找到重复的电子邮件?

SELECT b_email AS email FROM user WHERE status = 3 AND b_email != '' 
UNION (SELECT c_email AS email FROM user WHERE status = 3 AND c_email != '') 
UNION (SELECT user_email AS email FROM user WHERE status = 3 AND user_email != '') 
UNION (SELECT user_email AS email FROM sub_user WHERE status = 3 AND user_email != '') 
UNION (SELECT su_email AS email FROM sub_user WHERE status = 3 AND su_email != '') 
ORDER BY email ASC

谢谢。

4

1 回答 1

3

您的查询结果不会有重复项,因为UNION删除了重复项。要保留重复项,请UNION ALL改用:

SELECT b_email AS email FROM user WHERE status = 3 AND b_email != ''
UNION ALL SELECT c_email AS email FROM user WHERE status = 3 AND c_email != ''
...

要找出重复的电子邮件地址,您可以执行以下操作:

  • 更改您的查询以返回所有电子邮件地址的列表,包括重复项(这意味着使用UNION ALL而不是UNION
  • 用一个按电子邮件地址计数的外部查询包装它
  • 将外部查询结果限制为计数为两个或更多的电子邮件地址

以下是如何做到这一点(注意这是假设您发布的查询有效):

SELECT email, COUNT(*)
FROM (
  SELECT b_email AS email FROM user WHERE status = 3 AND b_email != '' 
  UNION ALL SELECT c_email AS email FROM user WHERE status = 3 AND c_email != ''
  UNION ALL SELECT user_email AS email FROM user WHERE status = 3 AND user_email != ''
  UNION ALL SELECT user_email AS email FROM sub_user WHERE status = 3 AND user_email != ''
  UNION ALL SELECT su_email AS email FROM sub_user WHERE status = 3 AND su_email != ''
) EmailGlom
GROUP BY email
HAVING COUNT(*) > 1

您的结果将是在内部查询中多次出现的每个电子邮件地址。

于 2013-03-21T03:31:52.377 回答