dongshi1934 2019-05-15 07:59
浏览 476
已采纳

如何在选择查询MySQL,Beego中选择特定ID的总和

I want to get a result like

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

A query that I trying to use

SELECT(SELECT SUM(paid_amount) WHERE ID = t1.**HERE**) AS sub1,
(t1.amount - sub1) AS sub2
FROM invoice t1 CROSS JOIN
invoice_paid t2;

Table struct in my DB

table invoice_paid        
------------------------------------
id | uuid | paid_date | paid_amount
------------------------------------
1  | ABC  | 2019/5/1  | 15
2  | ABC  | 2019/5/5  | 80 

table invoice
-------------------------------------------------------
id | uuid | user_id |created_date |    amount    | name 
-------------------------------------------------------
1  | ABC  |    1    |   2019/5/1  |      100     | xa
2  | PQR  |    2    |   2019/5/5  |      150     | xb

I can use sum only 1 condition like where id = 1 but how do I combine this query in select query with a join query. I use beego(golang), MariaDB

  • 写回答

1条回答 默认 最新

  • douyi6168 2019-05-15 08:13
    关注

    You can use this query. It JOINs the invoice table to a derived table of SUMs of all the amounts paid per invoice from invoice_paid, subtracting that total from the invoice amount to get the outstanding amount:

    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
    

    Output:

    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
    

    Demo on dbfiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助