从数据库中仅选择重复记录的mysql select查询

6

我正在尝试处理mysql数据库中的重复记录。然而,我不想删除这些记录,因为只有两列是重复的。我该如何找到这些重复的记录?


https://dev59.com/RXRA5IYBdhLWcg3wtwWe - gen_Eric
2个回答

10

你能提供有关表结构的更多信息吗?你所说的重复是指只有两列是重复的吗?

无论如何,你可以查看 GROUP BYCOUNTHAVING

SELECT `duped_field1`, `duped_field2`, COUNT(*) `tot`
FROM `table`
GROUP BY `duped_field1`, `duped_field2`
HAVING `tot` > 1

3

查找重复项的一般原则是使用group byhaving count(*) > 1

如果你只想知道重复的列值:

select col1, col2
from table
group by col1, col2
having count(*) > 1

然而,如果您想查看这两列重复的所有字段:

select t.*
from @tbl t
where exists (select * 
              from @tbl d 
              where d.col1 = t.col1 and d.col2 = t.col2
              group by d.col1 
              having COUNT(*) > 1)

或者简单地添加 * .. SELECT *, COUNT(*) tot - Fabrizio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接