【发布时间】:2013-05-18 05:51:27
【问题描述】:
让我们考虑下表-
ID Score
1 95
2 100
3 88
4 100
5 73
我是一个 SQL 新手,但如何返回包含 ID 2 和 4 的分数? 所以它应该返回 100,因为它在 ID 2 和 4 中都有特色
【问题讨论】:
标签: mysql sql relational-division
让我们考虑下表-
ID Score
1 95
2 100
3 88
4 100
5 73
我是一个 SQL 新手,但如何返回包含 ID 2 和 4 的分数? 所以它应该返回 100,因为它在 ID 2 和 4 中都有特色
【问题讨论】:
标签: mysql sql relational-division
这是“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”的分数。
【讨论】:
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 是一个唯一的列。
【讨论】:
id 不能保证唯一时,我们可以使用 COUNT(DISTINCT id) 代替 COUNT(*) b>.
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)
)
【讨论】: