我正在做一个关于使用PHP(使用Codeigniter)和MYSQL烹饪食谱的项目。
我有三张桌子:
Ingredients
- id
,name
。Recipe
- id
,name
ing_to_rep
- recipe_id
,ingredient_id
(我使用此表来保存哪种配方有哪些成分。)“获取所有有蛋(id = 64
)和盐(id = 65
)的食谱”的查询是什么
我试过了:
SELECT * FROM recipe JOIN ing_to_rep ON recipe.id = ing_to_rep.rep_id
WHERE ing_to_rep.ing_id = 64 AND ing_to_rep.ing_id = 65
当然,它只返回任何内容,但它可以帮助您获得我想要做的事情。
答案 0 :(得分:1)
可能有一种更有效的方式和更灵活的方式,但有两个子查询连接可以:
SELECT
recipe.*
FROM recipe
JOIN (SELECT recipe_id FROM ing_to_rep WHERE ingredient_id = 64) AS ing1 ON recipe.id = ing1.recipe_id
JOIN (SELECT recipe_id FROM ing_to_rep WHERE ingredient_id = 65) AS ing2 ON recipe.id = ing2.recipe_id
也可以使用EXISTS
SELECT
recipe.*
FROM
recipe
WHERE
EXISTS (SELECT recipe_id FROM ing_to_rep ing1 WHERE ingredient_id = 64 AND recipe.id = ing1.recipe_id)
AND EXISTS (SELECT recipe_id FROM ing_to_rep ing2 WHERE ingredient_id = 65 AND recipe.id = ing2.recipe_id)
答案 1 :(得分:1)
另一种解决方案就像是
SELECT * FROM recipe r JOIN
(SELECT recipe_id FROM ing_to_rep
GROUP BY recipe_id
HAVING SUM(IF(ingredient_id IN (64, 65), 1, 0)) = 2) gr ON r.id = gr.recipe_id
我不确定表现,你必须自己尝试。
答案 2 :(得分:0)
无子查询方法(CI的AR不支持子查询):
SELECT *
FROM recipe
JOIN ing_to_rep ON (ing_to_rep.id_recipe=recipe.id AND (ing_to_rep.ing_id=64 OR ing_to_rep.ing_id=65))
GROUP BY recipe.id
HAVING COUNT(ing_to_rep.ing_id)=2
您可以使用此解决方案CI的ActiveRecord。