mysql 分组错误

标签 mysql sql group-by where-clause

下面是我正在使用的查询

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/

相关文章:

mysql - 帮助进行高级 MySQL 优化

mysql - COUNT() 和 Left Join 不起作用

sql - 在 SQLite 中按月分组

mysql - 忽略类型转换 IN

mysql - MySQL 中按天分组的性能​​比较

sql - 如何从具有特定组计数的表中获取所有行?

mysql - 在 laravel 5 中使用 mysql json 字段而不是表上的许多可为空字段可能有什么缺点

mysql - 更新具有位置 mysql 的行

mysql - 使用不使用索引的查询变量进行选择

SQL - 按行对排序