mysql分组错误
下面是我正在使用的一个查询mysql分组错误,mysql,sql,group-by,where,Mysql,Sql,Group By,Where,下面是我正在使用的一个查询 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 `casho
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`
问题是我得到了一个错误:
组函数的使用无效
将where子句中的函数替换为字段别名“total”,仍然会出现错误:
未知列总数
如何修复此查询?使用HAVING而不是WHERE,并将GROUP BY NAME子句而不是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
试试这个:
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
作为使用HAVING子句的替代方法,您可以将查询包装在SELECT语句中,然后将筛选器放置在WHERE子句中:
你给这个取了个别名
(sum(cashin.amount) - sum(cashout.amount)) as total
那么为什么你不在这里使用它呢
WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0
只用
FROM `client`
还有这个
(sum(cashin.amount) - sum(cashout.amount)) as total // line 4
换成
WHERE total < 0
(amountin - amountout) as total
这对你有好处
(sum(cashin.amount) - sum(cashout.amount)) as total // line 4
(amountin - amountout) as total