为什么MySQL SUM查询仅返回一行?
我试图创建一个MySQL查询以返回数据库中每个帐户的所有语句余额的总和。查询如下所示:
SELECT SUM(balance), handle FROM statement_versionsINNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id;
当我这样做时,它只返回一行,其中有一个总余额和一个帐户(ID为1的帐户)。我想要的是退还所有帐户的对帐单余额。我将如何实现呢?
回答:
您可能需要按某种方式分组handle
(我想这与帐户ID有关?),否则MySQL将从您的中选择SUM
值JOIN
。添加GROUP
BY子句会使SUM
。中列的每个不同值发生GROUP BY
。将查询更改为:
SELECT SUM(balance), handle FROM statement_versionsINNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY handle;
如果handle
与不相关,accounts.id
并且您想要按进行分组accounts.id
,则将查询更改为:
SELECT SUM(balance), accounts.id FROM statement_versionsINNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY accounts.id;
以上是 为什么MySQL SUM查询仅返回一行? 的全部内容, 来源链接: utcz.com/qa/399356.html