col1 col2
A bear
A dog
A cat
B bear
B dog
B cat
C dog
C cat
D bear
D dog
D cat
E bear
E dog
E cat
F dog
F cat
如果我想选择至少有一行col2 = 'bear'
的所有col1值,我可以这样做:
SELECT col1
FROM mytable
WHERE col1 IN ('A','B','C')
GROUP BY col1
HAVING col2 = 'bear'
将返回A和B
但我想只选择col1中没有col2 = 'bear'
我在考虑NOT HAVING
,但这似乎不起作用。
任何想法?谢谢!
答案 0 :(得分:9)
SELECT m1.col1
FROM mytable m1
WHERE NOT EXISTS(SELECT NULL
FROM mytable m2
WHERE m2.col1 = m1.col1
AND m2.col2 = 'bear')
AND m1.col1 IN ('A', 'B', 'C')
答案 1 :(得分:6)
你也可以使用这个技巧:
SELECT col1
FROM mytable
WHERE col1 IN ('A','B','C')
GROUP BY col1
HAVING SUM(CASE col2 WHEN 'bear' THEN 1 ELSE 0 END)=0