MySQL:在许多字段中选择重复项

时间:2011-10-25 17:05:17

标签: mysql

我使用以下查询来选择重复的电子邮件:

SELECT email
                FROM contacts
                WHERE active = 1
                GROUP BY email
                HAVING ( COUNT(email) > 1)

在上面的情况中,如果两个用户拥有相同的电子邮件,则该查询将显示它们。但是,还有另一个名为email2的电子邮件字段,我可以这样做,以便比较许多电子邮件字段中的计数? (例如,如果用户的电子邮件等于另一个用户的email2,则会将其视为重复)

谢谢!

2 个答案:

答案 0 :(得分:2)

SELECT tmp.email FROM (
    SELECT email as email FROM contacts WHERE active = 1
    UNION ALL
    SELECT email2 as email FROM contacts WHERE email != email2 AND active = 1
) as tmp
GROUP by tmp.email
HAVING COUNT(tmp.email) > 1
P.S:我的语法可能不对,但这个想法应该是这样的。

答案 1 :(得分:-1)

SELECT email
FROM contacts
WHERE (email = email2) AND (active = 1)

如果我正确地解释你。或者您的意思是某些用户记录在一条记录的email字段中可能有“user@example.com”,而在另一条记录的email2字段中可能有相同的地址?那就是

SELECT primary.email, primary.id, secondary.id
FROM contacts AS primary
INNER JOIN contacts AS secondary ON (primary.email = secondary.email2)