我想得到这样的结果result -------------------------------------------------------id | uuid | user_id |created_date | amount | name -------------------------------------------------------1 | ABC | 1 | 2019/5/1 | 5 | xa2 | PQR | 2 | 2019/5/5 | 150 | xb我尝试使用的查询SELECT(SELECT SUM(paid_amount) WHERE ID = t1.**HERE**) AS sub1,(t1.amount - sub1) AS sub2FROM invoice t1 CROSS JOINinvoice_paid t2;我的数据库中的表结构table invoice_paid ------------------------------------id | uuid | paid_date | paid_amount------------------------------------1 | ABC | 2019/5/1 | 152 | ABC | 2019/5/5 | 80 table invoice-------------------------------------------------------id | uuid | user_id |created_date | amount | name -------------------------------------------------------1 | ABC | 1 | 2019/5/1 | 100 | xa2 | PQR | 2 | 2019/5/5 | 150 | xb我只能使用 sum 1 条件,如 where id = 1 但我如何将选择查询中的此查询与连接查询结合起来。我使用 beego(golang),MariaDB
1 回答
慕沐林林
TA贡献2016条经验 获得超9个赞
您可以使用此查询。它将invoice表连接到派生表SUMs,其中包含每张发票支付的所有金额invoice_paid,从发票金额中减去总计以获得未结金额:
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
- 1 回答
- 0 关注
- 115 浏览
添加回答
举报
0/150
提交
取消