2014-03-31 259 views
0

我希望我能夠很好地解釋這一點。SQL結果表滿足兩個條件

說我有這個表:

Owner 
+--------+--------+ 
| Name | Type | 
+--------+--------+ 
| Bob | Cat | 
| Bob | Dog | 
| Bob | Cow | 
| Tim | Dog | 
| Tim | Cat | 
| Ted | Cat | 
| Joe | Dog | 
| Joe | Cat | 
| Joe | Sheep | 
+--------+--------+ 

我試圖找到大家誰擁有所有的動物添了(這麼一隻貓和一隻狗)。這意味着喬和鮑勃會滿足這一點,但不是泰德,因爲他只有一種動物蒂姆有

我將如何去獲得這個結果?

所以我必須與所有蒂姆擁有該類型的表:

SELECT Type FROM Owner WHERE Name= 'Tim'; 

我如何得到它,這樣只有那些誰擁有這兩種類型的蒂姆已經獲得來自所有者的列表中選擇?

任何指導將不勝感激,在此先感謝。

回答

0
select name 
from owner 
where type in (select distinct type from owner where name = 'tim') 
group by name 
having count(distinct type) = (select count(distinct type) from owner where name = 'tim') 
0

如果你只是試圖讓所有誰比添has更多的動物的人,那麼你可以不喜歡它

select Name from owners 
group by Name 
having count(distinct [Type]) > (select count(distinct type) from owners 
where Name='tim') 
0

我認爲這是一個joingroup by問題。將Tim的記錄加入所有其他所有者,但在type字段中。然後做一個彙總,只保留記錄,所有的type的比賽:

select o.name 
from owner otim left join 
    owner o 
    on o.type = tim.type and o.name <> 'Tim' and otim.name = 'Tim' 
group by o.name 
having min(case when o.type is null then 0 else 1 end) = 0; 

注意,當重複type值是允許在這張桌子也可使用。