Mysql 来自另一个表的SUM()的条件?
我有这样的数据表Mysql 来自另一个表的SUM()的条件?,mysql,Mysql,我有这样的数据表 id | amount | payment | balance 1 | 200 | 200 | 0 2 | 300 | 250 | 50 表交易 ID | Amount 1 | 200 2 | 300 表付款 ID | Transaction | Amount 1 | 1 | 200 2 | 2 | 150 3 | 2 | 100 然后我使用查询 SELECT `tran
id | amount | payment | balance
1 | 200 | 200 | 0
2 | 300 | 250 | 50
表交易
ID | Amount
1 | 200
2 | 300
表付款
ID | Transaction | Amount
1 | 1 | 200
2 | 2 | 150
3 | 2 | 100
然后我使用查询
SELECT `transaction`.id AS `id`,
`transaction`.amount AS amount,
SUM(payment.amount) AS payment,
`transaction`.amount - SUM(payment.amount) AS balance
FROM `transaction`
LEFT JOIN payment
ON payment.`transaction` = `transaction`.id
GROUP BY payment.`transaction`;
然后我得到这样的数据
id | amount | payment | balance
1 | 200 | 200 | 0
2 | 300 | 250 | 50
现在,我如何使条件仅显示余额大于0的数据?它应该只显示行id 2 我试图做这个查询,但它给了我错误
SELECT `transaction`.id AS `id`,
`transaction`.amount AS amount,
SUM(payment.amount) AS payment,
`transaction`.amount - SUM(payment.amount) AS balance
FROM `transaction`
LEFT JOIN payment
ON payment.`transaction` = `transaction`.id
WHERE `transaction`.amount - SUM(payment.amount) > 0
GROUP BY payment.`transaction`;
谢谢你,GusdeHAVING”SQL子句满足您的需要。它类似于“WHERE”,只是它在join和groupby之后运行,并允许您根据几乎最终的输出进行过滤。它还可用于查找已连接在一起的表之间缺少的关系
SELECT `transaction`.id AS `id`,
`transaction`.amount AS amount,
SUM(payment.amount) AS payment,
`transaction`.amount - SUM(payment.amount) AS balance
FROM `transaction`
LEFT JOIN payment
ON payment.`transaction` = `transaction`.id
GROUP BY payment.`transaction`
HAVING balance > 0;