我有一个varchar列的表,我想找到在这个列中有重复值的所有记录。我可以使用什么查询来查找重复项?


当前回答

根据levik的回答来获取重复行的id,如果服务器支持的话,可以执行GROUP_CONCAT(这将返回一个以逗号分隔的id列表)。

SELECT GROUP_CONCAT(id), name, COUNT(*) c
FROM documents
GROUP BY name
HAVING c > 1;

其他回答

我看到上面的结果和查询将工作良好,如果你需要检查单列值是重复的。比如电子邮件。

但如果你需要检查更多的列,并希望检查结果的组合,那么这个查询将正常工作:

SELECT COUNT(CONCAT(name,email)) AS tot,
       name,
       email
FROM users
GROUP BY CONCAT(name,email)
HAVING tot>1 (This query will SHOW the USER list which ARE greater THAN 1
              AND also COUNT)
Select column_name, column_name1,column_name2, count(1) as temp from table_name group by column_name having temp > 1
SELECT * 
FROM `dps` 
WHERE pid IN (SELECT pid FROM `dps` GROUP BY pid HAVING COUNT(pid)>1)

我更喜欢使用窗口函数(MySQL 8.0+)来查找副本,因为我可以看到整行:

WITH cte AS (
  SELECT *
    ,COUNT(*) OVER(PARTITION BY col_name) AS num_of_duplicates_group
    ,ROW_NUMBER() OVER(PARTITION BY col_name ORDER BY col_name2) AS pos_in_group
  FROM table
)
SELECT *
FROM cte
WHERE num_of_duplicates_group > 1;

DB小提琴演示

SELECT varchar_col
FROM table
GROUP BY varchar_col
HAVING COUNT(*) > 1;