我知道有很多“类似”的问题,但我无法弄清楚如何使这项工作。我希望对其他人来说很简单!
我有一个如下所示的查询:
SELECT
d.name DishName,
alt.name AllergyName
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
GROUP BY d.id, alt.id
ORDER BY d.name
这给了我类似于以下内容的表格:
Dish Name | AllergyName
-----------------------------------------
Almond Pudding | NULL
Almond Pudding | Egg
Apple Cake | Milk
Apple Cake | Lactose
Apple Cake | Egg
Apple Cake | NULL
Avocado Chocolate Cream | Milk
Avocado Chocolate Cream | Lactose
Avocado Chocolate Cream | NULL
Avocado Chocolate Cream | Peanuts
Avocado Chocolate Cream | Tree Nuts
Avocado Chocolate Cream | Soy
Avocado Egg | NULL
Avocado Egg | Egg
Bacon Wrapped Asparagus | NULL
Baked Cauliflower | NULL
Baked Cauliflower | Milk
Baked Cauliflower | Lactose
Baked Salmon | NULL
Baked Salmon | Milk
Baked Salmon | Lactose
现在,我想做的是列出所有菜肴的清单,其中特定菜肴的任何过敏名称都不是“鸡蛋”等。
例如,如果我只想获得那些不能吃鸡蛋的菜,那么我会运行这个查询,并应该取回Avocado Chocolate Cream, Bacon Wrapped Asparagus, Baked Cauliflower and Baked Salmon
的菜肴。
我试图设置一些WHERE NOT IN和其他类似的,但我继续只从菜中取出某种成分而不是不选择菜。例如,在我尝试的查询中,使用'Egg'示例,Apple Cake仍然会返回,但是'Egg'的特定行现在不会显示。
答案 0 :(得分:2)
首先,考虑如何确定哪些菜肴中含有“蛋”。
SELECT
FoodAllergyTbl.dish_id
FROM
`meals_food_allergytypes` AS FoodAllergyTbl
INNER JOIN
`meals_allergytypes` AS AllergyTbl
ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
WHERE
AllergyTbl.name = 'Egg';
然后,您可以选择上面列表中没有id
的菜肴列表。
SELECT
name
FROM
`meal_dish`
WHERE
`id` NOT IN (
SELECT
FoodAllergyTbl.dish_id
FROM
`meals_food_allergytypes` AS FoodAllergyTbl
INNER JOIN
`meals_allergytypes` AS AllergyTbl
ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
WHERE
AllergyTbl.name = 'Egg'
);
答案 1 :(得分:0)
你可以用这种方式用于Dish Name,例如Egg:
select name
from meals_dish
where name not in (
SELECT distinct d.name
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
AND alt .AllergyName = 'Egg'
)