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添加条件,但显示错误,有人可以帮忙吗?
最佳答案
在聚合函数(例如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)
关于mysql - 如何使用MySQL查询添加更多条件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25431553/