我想在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

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


当前回答

Powerlord的答案确实是最好的,我建议再做一个改变:使用LIMIT来确保db不会超载:

SELECT firstname, lastname, list.address FROM list
INNER JOIN (SELECT address FROM list
GROUP BY address HAVING count(id) > 1) dup ON list.address = dup.address
LIMIT 10

如果没有WHERE和when连接,使用LIMIT是一个好习惯。从小值开始,检查查询有多重,然后增加限制。

其他回答

select * from table_name t1 inner join (select distinct <attribute list> from table_name as temp)t2 where t1.attribute_name = t2.attribute_name

对于你的桌子来说,应该是这样的

select * from list l1 inner join (select distinct address from list as list2)l2 where l1.address=l2.address

这个查询将为您提供列表表中所有不同的地址条目…我不知道这将如何工作,如果你有任何主键值的名称等。

我们也可以发现重复依赖于不止一个字段。对于这些情况,您可以使用下面的格式。

SELECT COUNT(*), column1, column2 
FROM tablename
GROUP BY column1, column2
HAVING COUNT(*)>1;

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

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

关键是重写这个查询,以便它可以用作子查询。

SELECT firstname, 
   lastname, 
   list.address 
FROM list
   INNER JOIN (SELECT address
               FROM   list
               GROUP  BY address
               HAVING COUNT(id) > 1) dup
           ON list.address = dup.address;

就我个人而言,这个问题解决了我的问题:

SELECT `SUB_ID`, COUNT(SRV_KW_ID) as subscriptions FROM `SUB_SUBSCR` group by SUB_ID, SRV_KW_ID HAVING subscriptions > 1;

这个脚本所做的是在表中显示所有存在过一次以上的订阅者ID,以及找到的重复的数量。

这是表的列:

| SUB_SUBSCR_ID | int(11)     | NO   | PRI | NULL    | auto_increment |
| MSI_ALIAS     | varchar(64) | YES  | UNI | NULL    |                |
| SUB_ID        | int(11)     | NO   | MUL | NULL    |                |    
| SRV_KW_ID     | int(11)     | NO   | MUL | NULL    |                |

希望对你也有帮助!