我的MySql查询需要帮助(从多个表中选择)

时间:2018-02-08 07:12:25

标签: mysql sql database

所以,我有3张桌子:

  1. PIZZA 与pizza_ID,pizza_title和pizza_price
  2. INGREDIENTS with ingredients_ID; ingredients_title和ingredients_description
  3. PIZZA_INGREDIENTS ID,pizza_id,ingredients_id
  4. 我需要从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不是我的强项,我感谢任何帮助。 感谢

1 个答案:

答案 0 :(得分:3)

尝试加入子查询,该子查询进行聚合以查找具有两种成分的所有比萨饼:

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;