How to return rows that have the same column values in MySql

前端 未结 3 1591
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:47

Lets consider the following table-

ID Score
1  95

2  100

3  88

4  100

5  73

I am a total SQL noob but how do I return the Scores featur

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 23:02

    This is an example of a "sets-within-sets" query. I recommend aggregation with the having clause, because it is the most flexible approach.

    select score
    from t
    group by score
    having sum(id = 2) > 0 and -- has id = 2
           sum(id = 4) > 0     -- has id = 4
    

    What this is doing is aggregating by score. Then the first part of the having clause (sum(id = 2)) is counting up how many "2"s there are per score. The second is counting up how many "4"s. Only scores that have at a "2" and "4" are returned.

提交回复
热议问题