[英]SQL(Left Join) Get all recipes which have all their ingredients in another table
[英]Return only recipes that contains all ingredients Sql
我有这 3 张桌子:
饮料
原料
操作者
Drinks
和Ingredients
在opskrifter
中交叉引用。
我想从opskrifter
返回所有包含另一张名为
库存
所以要制作杜松子酒和滋补品,我需要同时备有杜松子酒和滋补品。
如果我只有可乐和补品,我应该什么都不返回
这是我到目前为止所得到的,从其他帖子复制/粘贴,但无法进一步了解。
Select
d.*
From
drinks d
Where
not exists (select 1
from opskrifter r
where r.drink_id = d.drink_id
and r.ingredient_id in (1, 2, 3))
请帮忙:-)
您可以使用聚合:
select o.drink_id
from opskrifter o
where r.ingredient_id in (1, 2, 3)
group by o.drink_id
having count(*) = 3;
您可以使用join
, in
, exists
- 不管什么 - 从drinks
中引入整个行。
我想从
opskrifter
返回所有包含来自另一个名为stock
的表的成分的recipies。
我了解您想要的饮料含有stock
表中列出的所有成分。 假设您在stock
中有一个名为ingredient_id
的列,您可以将其表述为:
select o.drink_id
from opskrifter o
inner join stock s on s.ingredient_id = o.ingredient_id
group by o.drink_id
having count(*) = (select count(*) from stock)
或者,如果您想要所有成分都有stock
的饮料:
select o.drink_id
from opskrifter o
left join stock s on s.ingredient_id = o.ingredient_id
group by o.drink_id
having count(*) = count(s.ingredient_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.