我正在尝试计算子查询中的匹配数量,以便按结果排序。
我正在尝试查询:
SELECT recipes.*, (SELECT COUNT(ingredient_id) FROM recipes WHERE ingredient_id IN(1,3)) AS ingredient_matches
FROM recipes
INNER JOIN ingredients
ON recipes.id = ingredients.recipe_id
INNER JOIN ingredients_available
ON ingredients.ingredient_id = ingredients_available.id
GROUP BY recipes.id
ORDER BY ingredient_matches DESC;
数据库结构:
recipes:
id, name
ingredients:
id, recipe_id, ingredient_id
ingredients_available:
id, name
tags:
id, recipe_id, tag_id
tags_available:
id, name
下面的查询有效,但我希望能够拥有不匹配的访问成分,所以我可以说如果有意义的话他们需要它们吗?
SELECT recipes.*, COUNT(ingredients.id) AS ingredient_matches
FROM recipes
INNER JOIN ingredients
ON recipes.id = ingredients.recipe_id
INNER JOIN ingredients_available
ON ingredients.ingredient_id = ingredients_available.id
WHERE ingredient_id IN (1, 5)
GROUP BY recipes.id
ORDER BY ingredient_matches DESC;
答案 0 :(得分:1)
http://sqlfiddle.com/#!2/3f9ef/15
是理想的结果。这是因为我没有确定子查询中的recipes_id = ingredients.recipe_id。
答案 1 :(得分:0)
以下是否有效?:
SELECT recipes.*, COUNT(ingredients.id) AS ingredient_matches
FROM recipes
INNER JOIN ingredients
ON recipes.id = ingredients.recipe_id
LEFT JOIN ingredients_available
ON ingredients.ingredient_id = ingredients_available.id
WHERE ingredient_id IN (1, 5)
GROUP BY recipes.id
ORDER BY ingredient_matches DESC;