如何将这些查询组合在一起作为一个结果

时间:2016-05-28 02:43:52

标签: php mysql sql subquery

SELECT COUNT(recipe_id) AS Found
FROM recipe_ingredients R, users_ingredients U
WHERE R.key_ingredient = U.key_ingredient;

SELECT recipe_id, COUNT(recipe_id) As Count FROM recipe_ingredients GROUP BY recipe_id;

1 个答案:

答案 0 :(得分:2)

根据您的评论我理解的是您需要将三列显示为recipeId, foundIngredients, countIngredients

由于没有表模式,我假设了结构并派生了以下查询:

SQL小提琴是http://sqlfiddle.com/#!9/eee151/3

SELECT COU.recipe_id, IFNULL(FOU.Found, 0) AS Found, COU.Count
FROM  ( SELECT recipe_id, COUNT(recipe_id) As Count 
        FROM recipe_ingredients 
        GROUP BY recipe_id) COU
LEFT OUTER JOIN ( SELECT R.recipe_id, COUNT(R.key_ingredient) AS Found
        FROM users_ingredients U
        JOIN recipe_ingredients R ON R.key_ingredient = U.key_ingredient
        GROUP BY R.recipe_id) FOU ON FOU.recipe_id = COU.recipe_id