mysql通过查询

时间:2015-06-19 10:25:19

标签: mysql query-optimization

我有2张桌子"食谱"," recipes_items" ,在表recipes_items中,我有一个整数列" important"。现在我有一个查询,它通过一个子查询来提取由recipes_items.important的总和(重要)排序的食谱,订单:

(SELECT sum(...) from recipes_items...) DESC)

但我想要的是检索食谱中的附加列查询列的平均值"重要"来自table recipes_items 怎么会这样?

由于 摩西

select  recipes.recipeName,
        recipes.recipeID,
        AVG (recipes_items.importance) AS averageScore
    from  recipes,recipes_items
    WHERE  recipes_items.recipeID=recipes.recipeID
    ORDER BY  
      ( SELECT  SUM(recipes_items.importance) AS sumImportance
            FROM  recipes_items
            WHERE  recipes_items.recipeID = recipes.recipeID
              AND  recipes_items.itemID IN ('1059')
      ) DESC
    LIMIT  20

我希望得到的结果是来自recipes_items.itemID的重要性列的顺序,该列匹配' IN()'中的一组ID?部分,也希望将匹配ID的每一行中匹配ID的数量或总和加到recipes_items.itemID ......

1 个答案:

答案 0 :(得分:0)

您没有显示完整查询,但您可以在没有子查询的情况下执行此操作,但仍然包含平均值:

SELECT recipes.id, recipes.name, AVG(recipes_items.important)
FROM recipes
LEFT JOIN recipes_items ON (recipes.id = recipes_items.recipe_id)
GROUP BY recipes.id
ORDER BY SUM(recipes_items.important) DESC