我的数据库中有以下 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 秒)
并使用“和”结果没有
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)
任何帮助将非常感激!