我有几张 table :
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
我想找到哪个盒子里装着我的东西。 所以如果我问: 什么盒子里有 fork 和我的汽车玩具。 我想获取该盒子的 ID,在本例中为 1。
我该怎么做?
Sqlfiddle:http://sqlfiddle.com/#!4/11b0a/3/0
编辑: 更新了厨房上要键入的列名称。
编辑2: 最终的解决方案是这样的(感谢戈登):
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
可能是任一表。一种解决方案是 group by
和 union all
。这是一个通用方法,假设两个引用表中的 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 方言这样编写它。
关于sql - 通过查看第三个表来了解两个表是如何连接的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34435022/