如何返回MySql中具有相同列值的行

时间:2013-05-23 01:36:31

标签: mysql sql

让我们考虑下表 -

ID Score
1  95

2  100

3  88

4  100

5  73

我是一个完整的SQL菜鸟但是如何返回ID为2和4的得分? 所以它应该返回100,因为它在ID 2和4中都有特色

3 个答案:

答案 0 :(得分:7)

这是“sets-within-sets”查询的示例。我建议使用having子句进行聚合,因为这是最灵活的方法。

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

这样做是按分数汇总。然后having子句的第一部分(sum(id = 2))计算每个分数有多少“2”。第二个是计算多少“4”。只返回“2”和“4”的分数。

答案 1 :(得分:2)

SELECT score
FROM t
WHERE id in (2, 4)
HAVING COUNT(*) = 2 /* replace this with the number of IDs */

这将选择ID为2和4的行。HAVING子句确保我们找到了两行;如果其中任何一个缺失,计数将小于2。

这假设id是唯一列。

答案 2 :(得分:0)

select Score
from tbl a
where a.ID = 2 -- based off Score with ID = 2
    --include Score only if it exists with ID 6 also
    and exists (
        select 1
        from tbl b
        where b.Score = a.Score and b.ID = 6
    )
    -- optional?  ignore Score that exists with other ids as well
    and not exists (
        select 1
        from tbl c
        where c.Score = a.Score and c.ID not in (2, 6)
    )