我有树桌:
配方:
id | title | ....
recipe_ingredients:
recipe_id | ingredient_id
成分:
id | ingredient
每种食谱都含有与之相关的成分。
我写了一个查询,通过成分ID获取食谱ID,成分匹配计数,该配方的成分总数:
SELECT recipes.id, recipes.title, ing_match_count,
(
SELECT count(id)
FROM recipe_ingredients as ri
WHERE ri.recipe_id = recipes.id
) as recipe_ing_count
FROM recipes
RIGHT JOIN (
SELECT recipe_id, ingredients_id, COUNT(*) AS ing_match_count
FROM recipe_ingredients
WHERE ingredients_id IN (19, 25, 30, 40)
GROUP BY recipe_id
) AS ri
ON recipes.id = ri.recipe_id
ORDER BY ing_match_count DESC
问题是,我无法使用其他成分ID排除食谱。上面的查询搜索具有19,25,30,40个成分ID的配方。但我想排除食谱,例如22和23种成分。
因此,如果食谱有19和22成分id,它将不会显示。
答案 0 :(得分:3)
我喜欢将group by
与having
子句中的条件用于这些类型的查询。我发现这是最灵活的appraoch。
SELECT r.id, r.title,
SUM(ingredients_id IN (19, 25, 30, 40)) as ing_match_count,
COUNT(*) as recipe_ing_count
FROM recipes r JOIN
recipe_ingredients ri
ON ri.recipe_id = recipes.id
GROUP BY r.id, r.title
HAVING ing_match_count > 0 AND
SUM(ingredients_id in (22, 23)) = 0;