gpt4 book ai didi

mysql - 配方数据库,按成分搜索

转载 作者:可可西里 更新时间:2023-11-01 07:23:08 33 4
gpt4 key购买 nike

我的数据库中有以下 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 |
+-----------+---------------+

仅搜索一种成分的查询工作正常,并输出:

mysql> select r.recipe_id, r.name
-> from recipes r
-> inner join ingredient_index
-> on i.recipe_id = r.recipe_id
-> where
-> i.ingredient_id = 7;

+-----------+------------------+
| recipe_id | name |
+-----------+------------------+
| 1 | tomato goodness |
| 2 | meat deluxe |
| 3 | chicken surprise |
+-----------+------------------+

但是当使用或用于多种成分时,我们会得到这个

mysql> select r.name
-> from recipes r
-> inner join ingredient_index i
-> on i.recipe_id = r.recipe_id
-> where i.ingredient_id = 7 or i.ingredient_id = 5;

+------------------+
| name |
+------------------+
| tomato goodness |
| tomato goodness |
| meat deluxe |
| meat deluxe |
| chicken surprise |
+------------------+

集合中有 5 行(0.00 秒)

使用“and”结果什么都没有

    mysql>  select r.name
-> from recipes r
-> inner join ingredient_index i
-> on i.recipe_id = r.recipe_id
-> where i.ingredient_id = 7 and i.ingredient_id = 5;
Empty set (0.00 sec)

任何帮助将不胜感激!

最佳答案

由于一个食谱可以使用多种成分,而您正在寻找使用一种或多种指定成分的食谱,因此您应该使用 DISTINCT 关键字来防止出现重复的结果,其中一个食谱使用的成分超过指定 list 中的一种成分。此外,您可以使用 IN 子句来过滤多个成分 ID。

select DISTINCT r.name
from
recipes r
inner join ingredient_index i
on i.recipe_id = r.recipe_id
where i.ingredient_id IN (7, 5);

或者,如果您要查找使用列表中指定的所有成分的食谱,则可以按食谱名称对结果进行分组,并检查记录数是否与列表中的成分数相同。

select r.name
from
recipes r
inner join ingredient_index i
on i.recipe_id = r.recipe_id
where i.ingredient_id IN (7, 5)
GROUP BY r.name
HAVING COUNT(*) = 2

这是假设不会有具有相同 (recipe_id, ingredient_id) 元组的重复记录(最好使用 UNIQUE 约束来确保)。

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com