我有树表:
食谱:
id | title | ....
recipe_ingredients:
recipe_id | ingredient_id
配料:
id | ingredient
每个食谱都有n种相关的成分。
我编写了一个查询,该查询获取配方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,则不会显示该配方。
最佳答案
我喜欢将group by
与having
子句中的条件一起用于这些类型的查询。我发现这是最灵活的方法。
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;
关于mysql - 获取不包含X成分的食谱,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23389017/