2016-12-15 38 views
-1

的確切數量兩個表我有兩個表 曲目和標籤加入與項目

表軌道(T1)

id Name 
1 a 
2 b 
3 c 
4 d 

表標籤(T2)

id track_id name 
1 1  a1 
2 1  b1 
3 1  c2 
4 1  d2 
5 2  a3 
6 2  b3 
7 2  c2 
8 2  d2 
9 3  a1 
10 3  b1 
11 3  c3 
12 3  d3 
13 4  a1 
14 4  b2 
15 4  c3 
16 4  d1 

我想選擇具有a1和b1的曲目列表,以及這些標籤c2,c3中的一個或兩個。
查詢應通過軌道返回軌道1和3

+1

請提供所需的輸出。 –

回答

0

既然你只想要track_id,沒有必要對錶T1 。

select track_id 

from  t2 

where  name in ('a1','b1','c2','c3') 

group by track_id 

having count(case when name = 'a1' then 1 end) = 1 
     and count(case when name = 'b1' then 1 end) = 1 
     and count(case when name in ('c2','c3') then 1 end) > 0 
;     
+0

好的射擊做得很好Dudu。謝謝 :) –

1

集團只拿那些你在組中提到的條件

select t1.id, t1.name 
from t1 
join t2 on t1.id = t2.track_id 
group by t1.id, t1.name 
having sum(t2.name = 'a1') > 0 
    and sum(t2.name = 'b1') > 0 
    and sum(t2.name in ('c2','c3')) > 0 
+0

我得到未知的t2.name作爲錯誤 –

+0

請求是爲了track_id,所以不需要T1。 –

+0

@MohamedBenSalah:在你的問題中有一個具有這樣的列名的表。 –