MYSQL 中的 SUM(子查询)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8757061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:16:41  来源:igfitidea点击:

SUM(subquery) in MYSQL

mysqlsubqueryaggregation

提问by D?nu

Basically, I am trying the following:

基本上,我正在尝试以下操作:

SELECT m.col1, SUM(SELECT col5 FROM table WHERE col2 = m.col1)
FROM table AS m

This doesn't seem to work. Is there any solution?

这似乎不起作用。有什么解决办法吗?

回答by Mithrandir

Why don't you do this:

你为什么不这样做:

SELECT m.col1, (SELECT SUM(col5) FROM table WHERE col2 = m.col1)
FROM table AS m

回答by SergeS

yes - use joins

是 - 使用连接

SELECT m.col1, SUM(j.col5) FROM table AS m 
       JOIN table AS j ON j.col2 = m.col1 GROUP BY m.col1

回答by Rolice

Sum is used inside the second select, where we want to sum the column. The col2 may be ambiguous column, if such column exists in the table m.

Sum 用于第二个选择中,我们要在其中对列求和。如果表 m 中存在这样的列,则 col2 可能是不明确的列。

SELECT
    m.col1,
    (SELECT SUM(t.col5) FROM table AS t WHERE t.col2 = m.col1) AS sumcol
FROM table AS m