条件来自另一个表的SUM()?

时间:2011-09-21 17:59:59

标签: mysql

我有这样的数据2表

Transaction

ID | Amount
1  | 200
2  | 300

Payment

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`;

谢谢你,
Gusde

1 个答案:

答案 0 :(得分:2)

“HAVING”SQL子句可以满足您的需求。它类似于“WHERE”,除了它在JOINS和GROUP BY之后运行,并允许您根据几乎最终输出进行过滤。它对于找到你们加入的表之间缺少的关系也很有用。

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;