Is it possible for SQL to find records with duplicates?

故事扮演 提交于 2019-12-04 08:38:14

To get all names that exist more than once you can execute this statement:

SELECT Name FROM People GROUP BY Name HAVING COUNT(*)>1;

To get the IDs of the duplicates "1,3" concatenated that way use GROUP_CONCAT:

SELECT GROUP_CONCAT( ID SEPARATOR ',' )
FROM Table
GROUP BY Name
HAVING COUNT(*) > 1

Another - not necessarily efficient - way to do this is with a self-join:

SELECT P1.Id, P2.Id
  FROM People P1, People P2
 WHERE P1.Id < P2.Id
   AND P1.Name = P2.Name;

The first condition ensures that you only see the pair (1,3) and not the extraneous pairs (3,1) or the identical rows (1,1), (3,3).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!