mysql选择有多个n到n的

Mat*_*att 1 mysql

我有类似这样的表

recipes_tbl
| id | Recipe | Directions |

ingredients_tbl
| id | Ingrediant | Category |

recipe_to_ingredient
| id | id_recipe  | id_ingredient | Quantity
Run Code Online (Sandbox Code Playgroud)

我正在尝试构建一个查询"获取所有使用牛肉(id_ingredient 1)和土豆(id_ingredient 2)和... n"的食谱

我怀疑解决方案涉及某种奇特的连接...也许?

Ste*_*ott 6

SELECT     R.ID, R.Recipe, R.Directions
FROM       Ingredients_tbl I
           INNER JOIN recipe_to_ingredient RI ON I.id = RI.id_ingredient 
           INNER JOIN recipes_tbl R ON R.id = R.id_recipe  
WHERE      I.ID IN (1 ,2)
GROUP BY   R.ID, R.Recipe, R.Directions
HAVING     COUNT(*) > 1
Run Code Online (Sandbox Code Playgroud)

应该这样做,虽然这个例子中的成分被硬编码为只有1或2.我需要更多地了解你打算如何提供成分id以在这方面提供更多.

  • 应该`JOIN recipes_tbl R ON I.id = R.id_recipe`是`JOIN recipes_tbl R ON R.id = RI.id_recipe`? (2认同)