为什么MySQL SUM查询仅返回一行?

时间:2018-10-27 05:34:04

标签: mysql sql database join

我正在尝试创建一个MySQL查询以返回数据库中每个帐户的所有语句余额的总和。查询看起来像这样:

SELECT SUM(balance), handle FROM statement_versions
INNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id;

执行此操作时,它仅返回一行,其中有一个总余额和一个帐户(ID为1的帐户)。我想要的是退还所有帐户的对帐单余额。我将如何实现?

1 个答案:

答案 0 :(得分:2)

您需要按某种分组,可能是handle(我想这与帐户ID有关?),否则MySQL会SUM 全部 JOIN。添加GROUP BY子句会使SUM中的列的每个不同值都发生GROUP BY。将查询更改为:

SELECT SUM(balance), handle FROM statement_versions
INNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY handle;

如果handleaccounts.id不相关,并且您想获得按accounts.id分组的结果,请将查询更改为:

SELECT SUM(balance), accounts.id FROM statement_versions
INNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY accounts.id;