2014-04-02 33 views
0

我正在计算子查询内匹配的数量以排序结果。通过计数子查询内的匹配数量来订购查询

查询我想:

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; 

回答

1

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

当时所期望的结果。这是因为我没有确定子查询中的recipes_id = ingredients.recipe_id。

+1

对不起,我一直忙于跟进。很高兴你能解决,这是一个很好的! – SS781

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; 
+1

我刚刚更换第二内有LEFT JOIN加入... – SS781

+0

没有看到例如: 'SELECT *食谱,GROUP_CONCAT(ingredients.id, “:”,ingredients_available.name)AS all_ingredients,COUNT( ingredients.id)AS ingredient_matches FROM食谱 INNER JOIN成分 ON recipes.id = ingredients.recipe_id LEFT JOIN ingredients_available ON ingredients.ingredient_id = ingredients_available.id WHERE ingredient_id IN(1,2) GROUP BY recipes.id ORDER BY ingredient_matches DESC;' 我仍然无法访问all_i ngredients一个配方,只有匹配1,5 – Muggles

+0

的配料才有可能得到一个sql小提琴来测试这些呢?它应该让事情更容易,因为查询有点长... – SS781