我有几张桌子:
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。
我该怎么做?
Sqlfiddle:http://sqlfiddle.com/#!4 / 11b0a / 3/0
编辑:更新了厨房的列名称以键入。
Edit2:最终解决方案变成这样(谢谢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
可能对任何一个表都使用。一种解决方案是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方言中以这种方式编写它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句