如何使用MySQL查询添加更多条件?

时间:2014-08-21 16:40:37

标签: mysql sql

SELECT 
`loanac`.`id`, 
`loanac`.`name`, 
`loanac`.`lacc`, 
SUM(`loantrans`.`in`) as totalin, 
SUM(`loantrans`.`out`) as totalout

FROM loanac, loantrans
WHERE `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`

以上是我上面的查询,可以正常显示所有帐户,但是我需要查找SUM(out)>的帐户SUM(in)而不是所有帐户

我尝试使用AND添加条件,但显示错误,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:4)

对聚合函数(如SUM或COUNT)执行条件的方法是HAVING,而不是WHERE

SELECT loanac.id, loanac.name, loanac.lacc, loanac.phone, 
       SUM(loantrans.in) as totalin, SUM(loantrans.out) as totalout 
FROM loanac, 
     loantrans 
WHERE loanac.lacc=loantrans.account 
GROUP BY loanac.lacc
HAVING SUM(loantrans.out) > SUM(loantrans.in)

答案 1 :(得分:1)

尝试使用

SELECT loanac.id, 
loanac.name, 
loanac.lacc, 
loanac.phone, 
SUM(loantrans.in) as totalin, 
SUM(loantrans.out) as totalout 
FROM loanac, loantrans 
WHERE loanac.lacc=loantrans.account 
GROUP BY loanac.lacc 
HAVING SUM(out) > SUM (in)