Select where count of one field is greater than one

后端 未结 9 1198
说谎
说谎 2020-12-07 23:57

I want to do something like this:

SELECT * 
  FROM db.table 
 WHERE COUNT(someField) > 1

How can I achieve this in MySql?

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 00:14

    It should also be mentioned that the "pk" should be a key field. The self-join

    SELECT t1.* FROM db.table t1
    JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk 
    

    by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried

    SELECT * FROM db.table HAVING COUNT(someField) > 1

    above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.

提交回复
热议问题