我正在計算子查詢內匹配的數量以排序結果。通過計數子查詢內的匹配數量來訂購查詢
查詢我想:
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