mysql 通过查询从 order by 中选择平均值

Posted

技术标签:

【中文标题】mysql 通过查询从 order by 中选择平均值【英文标题】:mysql select an average from order by with a query 【发布时间】:2015-06-19 10:25:18 【问题描述】:

我有 2 个表 "recipes"、"recipes_items" ,在表 recipes_items 我有一个整数列“重要”。现在我有一个查询,它提取由 recipes_items.important 的总和(重要)排序的食谱,该顺序有一个子查询:

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

但我想要检索作为食谱中的附加列查询表 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 的数量或总和与recipes_items.itemID 匹配的每一行的ID ...

【问题讨论】:

请提供样本记录和预期答案 您希望将“recipes_items.important”的平均值作为另一列? 是的,完全一样,但通过查询保持顺序相同 【参考方案1】:

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

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

【讨论】:

谢谢@Jim,完整的查询是: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 匹配,也希望有数字或总和recipes_items.itemID.. 的匹配 ID 的每一行中的匹配 ID

以上是关于mysql 通过查询从 order by 中选择平均值的主要内容,如果未能解决你的问题,请参考以下文章

在 mysql 中使用 union 和 order by 子句

MySQL 查询优化与 group by 和 order by rand

使用 ORDER BY 和 INNER JOIN 优化 MySQL 查询(选择用户关注的位置)

MySql - 添加 Order by 时查询缓慢

MySQL 查询常用操作——排序 order by

使用 ORDER BY id 时 MySQL 查询慢