我有下表
|------------------------| | owner | animal | color | |------------------------| | John | dog | black | | Peter | dog | brown | | John | cat | green | | Lisa | dog | white | | Peter | cat | black | |------------------------|
我需要归还哪位老板有黑狗和绿猫,结果必须是'John'
我试了这个没有运气
SELECT owner FROM pets WHERE ( EXISTS ( SELECT * FROM pets WHERE animal = 'dog' AND color = 'black' ) AND EXISTS ( SELECT * FROM pets WHERE animal = 'cat' AND color = 'green' ) )
答案 0 :(得分:1)
选择那些与其中一只宠物有关的人:
select owner
from pets
where (animal, color) in ( ('dog', 'black'), ('cat', 'green'))
这也会归还只有黑狗或绿猫的主人,所以我们需要过滤掉那些有两只动物的人,可以使用group by
和having
条款来完成
select owner
from pets
where (animal, color) in ( ('dog', 'black'), ('cat', 'green'))
group by owner
having count(*) = 2;
SQLFiddle示例:http://sqlfiddle.com/#!15/4df52/1