我有一张桌子上的动物,其结构如下所示
AnimalId Feature Present
-------- ------- -------
1 Teeth Yes
1 Leg Yes
2 Teeth No
2 Leg Yes
3 Teeth Yes
3 Leg Yes
如果牙齿和腿都是'是',我需要检索动物 我写了一个像
这样的查询select distinct A1.AnimalId from Animal A1
inner join Animal A2 on
A1.AnimalId =
(select distinct A2.AnimalId from Animal A2
inner join Animal A3 on
A2.AnimalId =
(select distinct A3.AnimalId from Animal A3 where A3.Feature = 'Leg' and A3.Present = 'Yes' group by A3.AnimalId)
where A2.Feature = 'Teeth' and A2.Present = 'Yes' group by A2.AnimalId)
及其工作。
想知道有没有更好的方法来写这个并获得相同的结果。
答案 0 :(得分:2)
我喜欢使用group by
和having
来处理此类查询。在你的情况下:
select a.animalId
from animal a
where (a.feature = 'Teeth' and a.present = 'Yes') or
(a.feature = 'Leg' and a.present = 'Yes')
group by a.animalId
having count(distinct a.feature) = 2;
where
子句可以简化为:
where a.feature in ('Teeth', 'Leg') and a.present = 'Yes'