0
我想在兩個相關的表中獲得amount
列的總和。在兩個不同的相關表中獲得兩個字段的總和
發票表:
-----------------------------------------
| id | student_id | created | updated |
-----------------------------------------
| 5 | 25 | date | date |
-----------------------------------------
發票項目表:
------------------------------
| id | invoice_id | amount |
------------------------------
| 1 | 5 | 250 |
------------------------------
| 2 | 5 | 100 |
------------------------------
| 3 | 5 | 40 |
------------------------------
付款表:
------------------------------
| id | invoice_id | amount |
------------------------------
| 1 | 5 | 100 |
------------------------------
| 2 | 5 | 290 |
------------------------------
所需的輸出:
--------------------------------------
| id | invoiceTotal | paymentTotal |
--------------------------------------
| 1 | 390 | 390 |
--------------------------------------
我已經試過
SELECT
i.id,
sum(ii.amount) as invoiceTotal,
sum(p.amount) as paymentTotal
FROM
invoices i
LEFT JOIN
invoice_items ii ON i.id = ii.invoice_id
LEFT JOIN
payments p ON i.id = p.invoice_id
WHERE
i.student_id = '25'
GROUP BY
i.id
什麼這似乎做的是正確計算支付的總和,但invoice_items.amount
似乎已經由6重複查詢(這是payments
的編號)。
我已閱讀過SO here和here上的類似問題,但這些例子比我想要做的要複雜得多,我無法弄清楚要放在哪裏。
@Stidgeon好吧,我更新了問題。 – Joseph