所以,我有3个表:
我需要从PIZZA中选择包含2种成分的所有pizza_title。现在,我有这个:
SELECT pizza.pizza_ID, pizza.pizza_title, pizza.pizza_price, pizza_ingredients.ingredient_id
FROM pizza
JOIN pizza_ingredients ON pizza_ingredients.pizza_id=pizza.id
WHERE pizza_ingredients.ingredient_id='7' or pizza_ingredients.id='4'
GROUP BY pizza.id
这个代码返回所有含有成分7或成分4的比萨饼。我只需要有7和4的比萨饼...
SQL不是我的强项,我感谢任何帮助。谢谢
尝试加入子查询,该子查询进行聚合以查找具有两种成分的所有比萨:
SELECT p1.*
FROM pizza p1
INNER JOIN
(
SELECT pizza_id
FROM pizza_ingredients
GROUP BY pizza_id
HAVING COUNT(*) = 2
) p2
ON p1.pizza_id = p2.pizza_id;
如果我误解了你的问题的措辞,而你想要找到所有有两种特殊成分的比萨饼,而不考虑其他成分,那么使用这个查询:
SELECT p1.*
FROM pizza p1
INNER JOIN
(
SELECT pizza_id
FROM pizza_ingredients
WHERE ingredients_id IN (4, 7)
GROUP BY pizza_id
HAVING COUNT(DISTINCT ingredients_id) = 2
) p2
ON p1.pizza_id = p2.pizza_id;