下面是我正在使用的查询
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
用where alias 'total'
替换where子句中的函数我仍然收到错误:
Unknown column total
如何修复此查询?
答案 0 :(得分:1)
使用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
答案 1 :(得分:0)
试试这个::
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 total < 0
答案 2 :(得分:0)
作为使用HAVING
子句的替代方法,您可以将查询包装在SELECT
语句中,然后将过滤器放在WHERE
子句中:
select names,
amountin,
amountout,
total
from
(
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
) src
where total < 0
答案 3 :(得分:0)
你做了这个
的别名 (sum(cashin.amount) - sum(cashout.amount)) as total
总计为什么你不在这里使用它?
WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0
将其替换为
WHERE total < 0
和这个
FROM (`client`)
只需使用
FROM `client`
和这个
(sum(cashin.amount) - sum(cashout.amount)) as total // line 4
将其替换为
(amountin - amountout) as total
它会对你有用。