Opposite of Distinct in MySQL

后端 未结 3 1964
无人及你
无人及你 2021-02-05 02:40

I would like to know if there is an opposite of \"select distinct\" in sql ,so that i can use to get values from a table of only which has repeated multiple times.

Thank

相关标签:
3条回答
  • 2021-02-05 03:22

    You need a group by with a having clause, something like:

    select person, count(friends)
    from people
    group by person
    having count(friends) > 1
    

    This would give you a list of all people and their friend count, except for those poor sad soles who have been befriended by only their mothers or, worse yet, not even their mothers :-)

    You have to use having instead of where in this case, since the former filters after grouping while the latter filters before, and you don't have the information of aggregate functions like count() until after grouping has taken place.

    0 讨论(0)
  • 2021-02-05 03:24

    I was looking for something like this for a many-to-many join situation where I want to show how many duplicates exist in both tables. count(distinct col) wasn't exactly the right solution because result of '1' indicated that the column indeed had duplicates, but didn't say how many. The 'opposite of distinct' I used for this was an inversion using count(*): (count(*)-count(distinct col)+1) and it did the job fine.

    0 讨论(0)
  • 2021-02-05 03:25
    select some_column, count(*)
    from some_table
    group by 1
    having count(*) > 1;
    

    On databases like mysql, you may even omit selecting count(*) to leave just the column values:

    select some_column
    from some_table
    group by 1
    having count(*) > 1;
    
    0 讨论(0)
提交回复
热议问题