Betrachten wir die folgende Tabelle-
ID Score 1 95 2 100 3 88 4 100 5 73
Ich bin ein absoluter SQL-Neuling, aber wie kann ich einen Score zurückgeben, der die ID 2 und 4 enth?lt? Es sollte also 100 zurückgeben, da es sowohl in ID 2 als auch in 4 vorkommt
SELECT score FROM t WHERE id in (2, 4) HAVING COUNT(*) = 2 /* replace this with the number of IDs */
這將選擇 ID 為 2 和 4 的行。然后,HAVING
子句確保我們找到了這兩行;如果其中一個(gè)缺失,計(jì)數(shù)將小于 2。
這假設(shè) id
是唯一列。
這是“集合內(nèi)集合”查詢的示例。我建議使用 having
子句進(jìn)行聚合,因?yàn)樗亲铎`活的方法。
select score from t group by score having sum(id = 2) > 0 and -- has id = 2 sum(id = 4) > 0 -- has id = 4
這所做的是按分?jǐn)?shù)聚合。然后 having
子句的第一部分 (sum(id = 2)
) 計(jì)算每個(gè)分?jǐn)?shù)有多少個(gè)“2”。第二個(gè)是數(shù)“4”的個(gè)數(shù)。僅返回“2”和“4”的分?jǐn)?shù)。