考虑多列,使用MySQL查找重复项

时间:2016-12-13 12:27:23

标签: mysql

我需要找到基于相同email OR first_name, last_name组合 OR 相同birth_date的重复使用。我可以轻松尝试的是:

SELECT id, first_name, last_name
FROM users
where id IN (SELECT id
             from users
             GROUP BY email
             HAVING count(*) > 1)
GROUP BY email, id;

以上仅提供了重复的电子邮件详细信息,但我对基于first_name, last_name组合 OR 同样birth_date处理其他条件感到困惑。

是否可以在单个查询中实现它?

1 个答案:

答案 0 :(得分:1)

尝试执行三个单独查询的UNION,检查三个重复的标准:

SELECT id
FROM users
GROUP BY id
HAVING COUNT(DISTINCT email) > 1
UNION
(
    SELECT id
    FROM users t1
    INNER JOIN
    (
        SELECT firstname, lastname
        FROM users
        GROUP BY firstname, lastname
        HAVING COUNT(*) > 1
    ) t2
        ON t1.firstname = t2.firstname AND
           t1.lastname = t2.lastname
)
UNION
SELECT id
FROM users
GROUP BY id
HAVING COUNT(DISTINCT birthdate) > 1