通过查看第三个表找出两个表是如何连接的

Finding out how two tables are connected by looking in a third

我有几张桌子:

boxes Table         ToysTable       Kitchen Table
boxId | ID          Name  | ID      Type   |  ID
-------------      --------------   -----------
1   | TOY1        Ball    | TOY1     Fork  | KIT1
1   | TOY2        Car     | TOY2     Knife | KIT2
1   | KIT1        Puzzle  | TOY3     Spoon | KIT3
2   | KIT2

我想找到装我东西的盒子。 所以如果我问: 什么盒子里有一把叉子和我的汽车玩具。 我想获取那个盒子的 ID,在本例中为 1.

我该怎么做?

SQLfiddle:http://sqlfiddle.com/#!4/11b0a/3/0

编辑: 将厨房中的列名称更新为类型。

编辑2: 最终解决方案变成了这样(感谢 Gordon):

select b.boxid
from boxes b left join
     (select id, 'toy' type
      from toys t
      where t.name in ('Car', 'Fork')
      union all
      select id, 'kitchen' type
      from kitchen k
      where k.name in ('Car', 'Fork')
     ) tk
     on b.id = tk.id
group by b.boxid
having count(distinct tk.type) = 2;

这有点棘手,因为 id 可能是 table。一种解决方案是 group byunion all。这是一个通用的方法,假设两个引用 table 中的 id 具有不同的值:

select b.boxid
from boxes b left join
     (select id, name 
      from toys t
      union all
      select id, name
      from kitchen k
     ) tk
     on b.id = tk.id
group by b.boxid
having sum(case when tk.name = 'Car' then 1 else 0 end) > 0 and
       sum(case when tk.name = 'Fork' then 1 else 0 end) > 0;

注意:在 MySQL 中,我会将此查询写为:

select b.boxid
from boxes b left join
     (select id, name 
      from toys t
      where t.name in ('Car', 'Fork')
      union all
      select id, name
      from kitchen k
      where k.name in ('Car', 'Fork')
     ) tk
     on b.id = tk.id
group by b.boxid
having count(distinct name) = 2;

实际上,您可以用任何 SQL 方言这样写。