mysql - 右手表所有需要的连接

时间:2017-01-29 16:43:48

标签: mysql sql

我有t1:

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.pid的t2.ps中:

pid  vid
  1    1
  1    2
  2    1
  2    3

因此,没有为pid 1选择vid 3,因为ps 2不在vs ...中

我在这里加入了纠结...帮助?

1 个答案:

答案 0 :(得分:0)

您可以通过各种方式获得满足此条件的pid。这是一个:

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