2017-01-29 45 views
-1

我有T1:MySQL的 - 加入其中右手錶所有必要

vid vs 
1  1 
1  2 
1  3 
2  2 
2  3 
3  1 
3  3 

和T2

pid ps 
1  2 
1  3 
2  1 
2  3 

我只需要t2.pid,t1.vid所有需要t1.vs是在t2.ps用於相應t2.pid:

pid vid 
    1 1 
    1 2 
    2 1 
    2 3 

所以,VID 3沒有選擇的PID 1爲PS 2不VS ...

我越來越糾結在這裏加入...幫助?

+0

你能告訴你目前的查詢? –

+0

'right outer join'是什麼保留右手邊桌的所有值! –

回答

0

你可以得到pid s表示滿足各種方式這一條件。這裏是一個:

select t2.pid 
from t2 left join 
    t1 
    on t2.pid = t1.vid 
group by t2.pid 
having count(*) = count(t1.vid); -- all are present 

然後,您可以使用此查詢中得到你想要的東西:

select t2.* 
from t2 join 
    (select t2.pid 
     from t2 left join 
      t1 
      on t2.pid = t1.vid 
     group by t2.pid 
     having count(*) = count(t1.vid) 
    ) tt2 
    on t2.pid = tt2.pid; 

最後,你可以得到ps值列表,只是用聚合:

select t2.pid, group_concat(t2.ps) 
from t2 left join 
    t1 
    on t2.pid = t1.vid 
group by t2.pid 
having count(*) = count(t1.vid); -- all are present 
相關問題