mysql – 食谱数据库,按成分搜索
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了mysql – 食谱数据库,按成分搜索,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2776字,纯文字阅读大概需要4分钟。
内容图文
我的数据库中有以下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 |
+-----------+---------------+
只搜索一种成分的查询工作正常,并输出:
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秒)
并且没有使用“和”结果
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关键字来防止配方使用指定列表中的多种成分时出现重复结果.此外,您可以使用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 – 食谱数据库,按成分搜索全部内容,希望文章能够帮你解决mysql – 食谱数据库,按成分搜索所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。