我正在计算子查询内匹配的数量以排序结果。通过计数子查询内的匹配数量来订购查询
查询我想:
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;
对不起,我一直忙于跟进。很高兴你能解决,这是一个很好的! – SS781