簡體   English   中英

避免多次連接同一張表的更好方法

[英]Better way to avoid joining the same table multiple times

我有一張動物表,結構如下

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)

及其工作。

我想知道有沒有更好的方法可以編寫並達到相同的結果。

我喜歡使用group byhaving來處理這種類型的查詢。 在您的情況下:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM