我有三个表,我需要单独的总金额。我还将在 select 或 where 子句中使用字段。
SELECT i.*, x.* FROM items AS i
LEFT JOIN
(
SELECT
p.item_id
,SUM(p.amount) AS saleAmount
,SUM(IF(p.type=1,pa.amount,0)) AS paidAmount
FROM payments AS p
LEFT JOIN payment_actions AS pa ON pa.payment_id=p.id
GROUP BY p.id
) AS x ON x.item_id=i.id
项目表;
id
---
1
付款表;
id | item_id | amount
---------------------------
1 | 1 | 300
payment_actions 表;
id | payment_id | amount
---------------------------
1 | 1 | 100
1 | 1 | 50
结果应该是;
saleAmount | paidAmount
--------------------------
300 | 150