下面是我正在使用的查询
SELECT
`names`, sum(cashin.amount) as amountin,
sum(cashout.amount) as amountout,
(sum(cashin.amount) - sum(cashout.amount)) as total
FROM (`client`)
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id`
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id`
WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0
GROUP BY `client`.`id`
问题是我得到一个错误:
Invalid use of group function
用字段别名 'total'
替换 where 子句中的函数我仍然得到错误:
Unknown column total
如何修复这个查询?
最佳答案
使用HAVING
代替WHERE
,并在前面放置GROUP BY names
子句而不是GROUP BY id
HAVING
子句如下:
SELECT
`names`,
sum(cashin.amount) as amountin,
sum(cashout.amount) as amountout,
(sum(cashin.amount) - sum(cashout.amount)) as total
FROM client
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id`
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id`
GROUP BY names
HAVING (sum(cashin.amount) - sum(cashout.amount)) < 0
关于mysql 分组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13800074/