食品配料复杂查询
Food Ingredients Complex Query
嗨,我有 3 个表,分别命名为:食物、配料和 foods_ingredients(多对多关系)
每种成分有 expires_at 和存货 属性
我想编写一个复杂的查询,使我能够按库存和过期日期获取食品名称
这是我自己的查询,但过期比较不起作用
SELECT *
FROM `foods`
LEFT JOIN `foods_ingredients` ON foods_ingredients.food_id = foods.id
LEFT JOIN `ingredients` ON foods_ingredients.ingredient_id = ingredients.id
WHERE foods.id IN
(SELECT `food_id`
FROM `ingredients`
LEFT JOIN `foods_ingredients` ON foods_ingredients.ingredient_id = ingredients.id
WHERE ingredients.stock > 0 AND ingredients.expires_at > CURRENT_DATE)
ORDER BY `best_before` DESC;
这将选择所有食品和 food_items 所有成分(对于这些食品)都存在(未过期,库存 gt 0):
SELECT *
FROM `foods` f
INNER JOIN `foods_ingredients` fi
ON fi.food_id = f.id
INNER JOIN `ingredients` i
ON fi.ingredient_id = i.id
WHERE NOT EXISTS
(SELECT *
FROM `ingredients` ib
INNER JOIN
`foods_ingredients` fib
on ib.id=fib.ingredient_id
WHERE fib.food_id=f.f.food_id
and (ib.stock = 0 or ib.expires_at <= CURRENT_DATE)
)
ORDER BY `best_before` DESC
假设您不希望看到 foods/food_items 该食品的一种或多种成分是库存=0 还是过期。
它还假设您在所有表中都有所有成分的相关行(存在行),即使这些成分是零库存或过期。
嗨,我有 3 个表,分别命名为:食物、配料和 foods_ingredients(多对多关系)
每种成分有 expires_at 和存货 属性
我想编写一个复杂的查询,使我能够按库存和过期日期获取食品名称
这是我自己的查询,但过期比较不起作用
SELECT *
FROM `foods`
LEFT JOIN `foods_ingredients` ON foods_ingredients.food_id = foods.id
LEFT JOIN `ingredients` ON foods_ingredients.ingredient_id = ingredients.id
WHERE foods.id IN
(SELECT `food_id`
FROM `ingredients`
LEFT JOIN `foods_ingredients` ON foods_ingredients.ingredient_id = ingredients.id
WHERE ingredients.stock > 0 AND ingredients.expires_at > CURRENT_DATE)
ORDER BY `best_before` DESC;
这将选择所有食品和 food_items 所有成分(对于这些食品)都存在(未过期,库存 gt 0):
SELECT *
FROM `foods` f
INNER JOIN `foods_ingredients` fi
ON fi.food_id = f.id
INNER JOIN `ingredients` i
ON fi.ingredient_id = i.id
WHERE NOT EXISTS
(SELECT *
FROM `ingredients` ib
INNER JOIN
`foods_ingredients` fib
on ib.id=fib.ingredient_id
WHERE fib.food_id=f.f.food_id
and (ib.stock = 0 or ib.expires_at <= CURRENT_DATE)
)
ORDER BY `best_before` DESC
假设您不希望看到 foods/food_items 该食品的一种或多种成分是库存=0 还是过期。
它还假设您在所有表中都有所有成分的相关行(存在行),即使这些成分是零库存或过期。