mysql组错误

时间:2012-12-10 11:28:34

标签: 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 `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

如何修复此查询?

4 个答案:

答案 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 

它会对你有用。