【问题标题】:SQL: how to select something using information from another tableSQL:如何使用来自另一个表的信息来选择某些东西
【发布时间】:2015-04-23 00:44:58
【问题描述】:

我有两个 SQL 表。

在第一个表中,每一行都有(在与问题无关的其他字段中)scorecategory_id 字段

第二个表 (categories) 是一个表,其中列出了第一个表中的元素可以属于的所有可能类别。

我想做以下 SQL 请求:

SELECT category_name, ( ??? ) AS category_score
FROM categories
ORDER BY category_score DESC

??? = the sum of the scores of all the elements in table 1 that belong to the category.

【问题讨论】:

    标签: mysql sql select


    【解决方案1】:

    你可以joingroup by

    SELECT   category_name, SUM(score) AS category_score
    FROM     categories c
    JOIN     element e ON c.category_id = e.category_id
    GROUP BY category_name 
    ORDER BY 2 DESC
    

    【讨论】:

    • 感谢您的回答,我不知道group by,我会调查一下。只是一个简单的问题,我没有得到ORDER BY 2 DESC 部分?例如,为什么不是GROUP BY category_score DESC
    • @Malimalo group by 子句将结果分解为组,以便可以将聚合函数(如sum)独立地应用于category_name 的每个唯一值。完成此操作后,仍需要对结果进行排序,这是通过 order by 子句完成的。
    • 谢谢你的回答,其实是我没有得到order by中的2。但我在问之前做了我应该做的事情,用谷歌搜索并很快得到了我的答案(这意味着order by the second element of select line)。谢谢你的帮助;)
    猜你喜欢
    • 2010-12-07
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多