我有两张桌子
Bills
:id amount reference
Transactions
:id reference amount
以下 SQL 查询
SELECT
*,
(SELECT SUM(amount)
FROM transactions
WHERE transactions.reference = bils.reference) AS paid
FROM bills
GROUP BY id HAVING paid<amount
用于 table 中的某些行Bills
,添加一个paid
包含相关交易金额总和的列。
但是,它仅在每张账单至少有一笔交易时才有效。否则,不返回无交易账单行。
可能,那是因为我应该进行内部连接!
所以我尝试以下方法:
SELECT
*,
(SELECT SUM(transactions.amount)
FROM transactions
INNER JOIN bills ON transactions.reference = bills.reference) AS paid
FROM bills
GROUP BY id
HAVING paid < amount
但是,这会为所有行返回相同的支付值!我究竟做错了什么 ?