我的数据库中有以下3个表,但是在查询我想要的结果时遇到了一些问题。我正在尝试按成分搜索食谱。
SQL小提琴:Fiddle
这是我的表格: 成分
+---------------+---------+
| ingredient_id | name |
+---------------+---------+
| 1 | tomato |
| 2 | onion |
| 3 | rice |
| 4 | chicken |
| 5 | beef |
| 6 | noodles |
| 7 | salt |
+---------------+---------+
食谱
+-----------+------------------+
| recipe_id | name |
+-----------+------------------+
| 1 | tomato goodness |
| 2 | meat deluxe |
| 3 | chicken surprise |
+-----------+------------------+
Ingredient_Index
+-----------+---------------+
| recipe_id | ingredient_id |
+-----------+---------------+
| 1 | 1 |
| 1 | 5 |
| 1 | 7 |
| 2 | 5 |
| 2 | 6 |
| 2 | 7 |
| 3 | 4 |
| 3 | 3 |
| 3 | 7 |
+-----------+---------------+
我想要实现的目标,是过滤我可以使用指定成分制作的所有食谱。这就是问题所在:
此查询:
select DISTINCT r.name
from
recipes r
inner join ingredient_index i
on i.recipe_id = r.recipe_id
where i.ingredient_id IN (2, 7, 5);
给我错误的结果,因为我没有足够的成分来制作任何食谱,但我仍然得到一个我可以制作所有食谱的结果。这是因为 recipe_id 在 Ingredient_Index 表中重复。
任何帮助都会让我非常感激。
答案 0 :(得分:2)
正如jarlh所说,检查没有丢失的成分:
select DISTINCT r.name
from recipes r
where not exists (
select 1 from ingredient_index i where r.recipe_id=i.recipe_id and i.ingredient_id not in (2,5,7)
)
答案 1 :(得分:0)
我遵循jarlh给出的另一个建议,并检查是否所有成分都可用:
select distinct a.name
from (select r.name, count(*) as ing_available
from
recipes r
inner join ingredient_index i
on i.recipe_id = r.recipe_id
where i.ingredient_id IN (1, 7, 5)
group by r.recipe_id)
as a join
(select r.name, count(*) as ing_required
from
recipes r
inner join ingredient_index i
on i.recipe_id = r.recipe_id
group by r.recipe_id)
as p
on p.ing_required = a.ing_available
答案 2 :(得分:0)
另一种方式:
select r.name
from recipes r
join ingredient_index i on i.recipe_id = r.recipe_id
where i.ingredient_id IN (2, 7, 5)
group by r.name
having count(i.ingredient_id) = 3