我想要得到这样的结果
ENTRYPOINT node dist/main.js
我尝试使用的查询
result
-------------------------------------------------------
id | uuid | user_id |created_date | amount | name
-------------------------------------------------------
1 | ABC | 1 | 2019/5/1 | 5 | xa
2 | PQR | 2 | 2019/5/5 | 150 | xb
数据库中的表结构
SELECT(SELECT SUM(paid_amount) WHERE ID = t1.**HERE**) AS sub1,
(t1.amount - sub1) AS sub2
FROM invoice t1 CROSS JOIN
invoice_paid t2;
我只能使用总和1个条件,例如id = 1,但是如何在选择查询中将此查询与联接查询结合起来。 我使用beego(golang),MariaDB
答案 0 :(得分:1)
您可以使用此查询。它将invoice
表加入到SUM
每张发票的所有已支付金额的invoice_paid
s的派生表中,从发票金额中减去该总数即可得到未付金额:
SELECT i.id, i.uuid, i.user_id, i.created_date, i.amount - COALESCE(p.amount, 0) AS amount, i.name
FROM invoice i
LEFT JOIN (SELECT uuid, SUM(paid_amount) AS amount
FROM invoice_paid
GROUP BY uuid) p ON p.uuid = i.uuid
ORDER BY i.id
输出:
id uuid user_id created_date name amount
1 ABC 1 2019-05-01 00:00:00 xa 5
2 PQR 2 2019-05-05 00:00:00 xb 150