为所有用户提供重复的电子邮件地址

时间:2013-09-18 14:26:04

标签: mysql sql

我正在编写MySQL查询,我可以从用户表中获取所有带有重复电子邮件地址的记录。

这是我到目前为止的查询..我的PHPMyAdmin一直在加载:

select personal_email, userid
from user
where personal_email in (
select personal_email
from user
group by personal_email
having count(personal_email) > 1);

如果我使用下面的查询,我只会收到所有双重电子邮件:

select personal_email, count(personal_email)
from user
group by personal_email
having count(personal_email) > 1

目标是获取包含重复电子邮件的所有记录。

4 个答案:

答案 0 :(得分:4)

使用JOIN而不是IN尝试查询:

SELECT  user.personal_email, user.userid
FROM    user 
        INNER JOIN
        (   SELECT  personal_email
            FROM    User
            GROUP BY personal_email
            HAVING COUNT(*) > 1
        ) dupe
            ON dupe.personal_email = user.personal_email;

MySQL通常会更好地优化INNER JOIN。

答案 1 :(得分:4)

在MySQL中执行此操作的最有效方法可能是使用exists子句:

select u.*
from user u
where exists (select 1
              from user u2
              where u.personal_email = u2.personal_email and
                    u.userid <> u2.userid
             );

为获得最佳效果,请在user(personal_email, userid)上创建索引。

答案 2 :(得分:1)

您可以将该结果用作选择标准

select * from user where personal_email IN (

   select personal_email
   from user
   group by personal_email
   having count(personal_email) > 1 );

A sqlfiddle for you

答案 3 :(得分:0)

您可以通过电子邮件将表格加入自己:

select distinct u1.personal_email, u1.userid
from user u1
join user u2 on u2.personal_email = u2.personal_email
    and u2.userid != u1,userid

这项工作的关键是将u2.userid != u1,userid添加到连接条件,以防止行加入自身。