简体   繁体   English

仅返回包含所有成分的食谱 Sql

[英]Return only recipes that contains all ingredients Sql

I have these 3 tables:我有这 3 张桌子:

Drinks饮料

  • drink_id饮料ID
  • name姓名

Ingredients原料

  • ingredient_id成分ID
  • name姓名

Opskrifter操作者

  • drink_id饮料ID
  • ingredient_id成分ID
  • quantity数量

Drinks and Ingredients are cross-referenced in opskrifter . DrinksIngredientsopskrifter中交叉引用。

I want to return all recipes from opskrifter that have ingredients from another table called我想从opskrifter返回所有包含另一张名为

Stock库存

  • name姓名

So to make a gin and tonic, I need to have both gin and tonic in stock.所以要制作杜松子酒和滋补品,我需要同时备有杜松子酒和滋补品。

If I only have coke and tonic, I should return nothing如果我只有可乐和补品,我应该什么都不返回

This is what I've got so far, copy/pasted from other post, but can't get any further.这是我到目前为止所得到的,从其他帖子复制/粘贴,但无法进一步了解。

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))

Please help:-)请帮忙:-)

You can use aggregation:您可以使用聚合:

select o.drink_id
from opskrifter o
where r.ingredient_id in (1, 2, 3)
group by o.drink_id
having count(*) = 3;

You can use join , in , exists -- whatever -- to bring in the entire row from drinks .您可以使用join , in , exists - 不管什么 - 从drinks中引入整个行。

I want to return all recipies from opskrifter that has ingredients from another table called stock .我想从opskrifter返回所有包含来自另一个名为stock的表的成分的recipies。

I understand that you want drinks that have all ingredients that are listed in the stock table.我了解您想要的饮料含有stock表中列出的所有成分。 Assuming that you have a column called ingredient_id in stock , you could phrase this as:假设您在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)

Alternatively, if you want drinks whose all ingredients are available in 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM