mysql - 食谱数据库,按成分搜索

标签 mysql sql database filter

我的数据库中有以下 3 个表,但在查询它们以获得我想要的结果时遇到一些问题。我正在尝试按成分搜索食谱。

SQL fiddle :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 |
+-----------+------------------+

成分索引

+-----------+---------------+
| 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_idIngredient_Index 表中重复。

任何帮助我都会非常感激。

最佳答案

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

关于mysql - 食谱数据库,按成分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453267/

相关文章:

字段名相同时的SQL连接

java - 您好,我尝试将数据库中的字符串值转换为 int,但没有发生

php - 搜索已登录用户的名称

php - 使用 Smarty php 显示 mysql 查询

MYSQL 查询 DateTime,查找现有预订

php - 如何将表与 PHPMYADMIN 中的列名一起导出为 CSV

php - PHP 中的 MYSQL UPDATE 和 SET 语句(500 错误响应)

PHP:文件或数据库

sql - 我可以将存储过程的结果放入 SQL 中另一个存储过程的游标中吗

database - 如何说服某人规范化数据库?