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

li9yvcax  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(374)

让我们考虑下表-

ID Score
1  95

2  100

3  88

4  100

5  73

我是一个彻头彻尾的SQLNoob,但是如何返回ID2和ID4的分数呢?所以它应该返回100,因为它在ID2和ID4中都有特性

xcitsw88

xcitsw881#

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 是唯一的列。

ktca8awb

ktca8awb2#

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)
    )
cgyqldqp

cgyqldqp3#

这是“集合中的集合”查询的一个示例。我建议用 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”的分数。

相关问题