Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql分组错误_Mysql_Sql_Group By_Where - Fatal编程技术网

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