2

下面是我正在使用的查询

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 子句中的函数'total'我仍然得到一个错误:

Unknown column total

如何修复此查询?

4

4 回答 4

1

使用HAVING代替WHERE,并在子句之前放置GROUP BY names子句代替,如下所示:GROUP BY idHAVING

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 
于 2012-12-10T11:30:11.653 回答
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
于 2012-12-10T11:31:56.053 回答
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
于 2012-12-10T11:33:07.647 回答
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 

它会对你有好处。

于 2012-12-10T12:08:47.307 回答