我试图计算子查询中匹配项的数量,以对结果进行排序。

查询我正在尝试:

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;

最佳答案

http://sqlfiddle.com/#!2/3f9ef/15

是理想的结果。这是因为我不确定子查询中的recipes_id = Ingredients.recipe_id。

关于mysql - 计算子查询中的匹配项数量以按以下顺序对查询进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22799827/

10-10 06:55