我在MySQL中有一个像这样的表:
ID name email
1 john abc@abc.com
2 johnny abc@abc.com
3 jim eee@eee.com
4 Michael abec@awwbc.com
如何让MySQL查询列出这样的副本?
重复搜索的结果:
ID name email Duplicate
1 john abc@abc.com 2
2 johnny abc@abc.com 2
答案 0 :(得分:27)
SELECT a.*, b.totalCount AS Duplicate
FROM tablename a
INNER JOIN
(
SELECT email, COUNT(*) totalCount
FROM tableName
GROUP BY email
) b ON a.email = b.email
WHERE b.totalCount >= 2
为了获得更好的效果,请在列INDEX
上添加EMail
。
OR
SELECT a.*, b.totalCount AS Duplicate
FROM tablename a
INNER JOIN
(
SELECT email, COUNT(*) totalCount
FROM tableName
GROUP BY email
HAVING COUNT(*) >= 2
) b ON a.email = b.email
答案 1 :(得分:2)
如果您可以使用逗号分隔列表中的ID和名称,那么您可以尝试:
select email, count(*) as numdups,
group_concat(id order by id), group_concat(name order by id)
from t
group by email
having count(*) > 1
这会保存连接,但结果不是关系格式。
答案 2 :(得分:0)
检查this post上的MySQL forums,其中包含以下内容:
SELECT t1.id, t1.name, t1.email FROM t1 INNER JOIN (
SELECT colA,colB,COUNT(*) FROM t1 GROUP BY colA,colB HAVING COUNT(*)>1) as t2
ON t1.email = t2.email;