我想在MySQL数据库中取出重复的记录。这可以用:

SELECT address, count(id) as cnt FROM list
GROUP BY address HAVING cnt > 1

结果是:

100 MAIN ST    2

我想要拖动它,以便它显示复制的每一行。喜欢的东西:

JIM    JONES    100 MAIN ST
JOHN   SMITH    100 MAIN ST

有什么想法可以做到吗?我试图避免做第一个,然后在代码中用第二个查询查找重复。


当前回答

会是这样的:

SELECT  t1.firstname t1.lastname t1.address FROM list  t1
    INNER JOIN  list t2 
    WHERE 
        t1.id < t2.id AND 
        t1.address = t2.address;

其他回答

另一个解决方案是使用表别名,如下所示:

SELECT p1.id, p2.id, p1.address
FROM list AS p1, list AS p2
WHERE p1.address = p2.address
AND p1.id != p2.id

在这种情况下,您真正要做的是获取原始的列表表,从中创建两个假装的表——p1和p2,然后在地址列上执行连接(第3行)。第4行确保相同的记录不会在结果集中多次出现(“重复重复”)。

为什么不直接INNER JOIN表本身呢?

SELECT a.firstname, a.lastname, a.address
FROM list a
INNER JOIN list b ON a.address = b.address
WHERE a.id <> b.id

如果地址可能存在两次以上,则需要DISTINCT。

不是很有效,但应该可以工作:

SELECT *
FROM list AS outer
WHERE (SELECT COUNT(*)
        FROM list AS inner
        WHERE inner.address = outer.address) > 1;

最快重复项删除查询过程:

/* create temp table with one primary column id */
INSERT INTO temp(id) SELECT MIN(id) FROM list GROUP BY (isbn) HAVING COUNT(*)>1;
DELETE FROM list WHERE id IN (SELECT id FROM temp);
DELETE FROM temp;
 SELECT firstname, lastname, address FROM list
 WHERE 
 Address in 
 (SELECT address FROM list
 GROUP BY address
 HAVING count(*) > 1)