如何在mysql中插入一个表的列之和作为另一个表的列的值?

hjzp0vay  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(291)

我有两张table叫 'register' 以及 'customer' . 寄存器表如下所示:

id     customer_id     purchase     paid     discount     return     previous_due
1      97              500          200      50                      100
2      98              1500         700      150                     500
3      97                                                 70
4      99              900          900      0                       1000
5      98                           200
6      99              1200         1000

我需要按customer\u id计算每列的总和,并自动更新'customer'表的列客户的表如下所示:

customer_id  tot_pur  tot_paid  tot_disc  tot_return  tot_due  final_due
97           500      200       50        0           100      350
98
99
``` `final_due` 列的计算方式如下 `(tot_pur + tot_due) - (tot_paid + tot_disc + tot_return)` 我不擅长mysql,所以最好简单的方法可以救我。感谢您的帮助。提前谢谢。
6uxekuva

6uxekuva1#

老实说,除非您需要这些金额以 lightning 般的速度随时可用,否则我建议您只需分别存储每个事务的值,然后创建一个按客户聚合并查找金额的视图:

CREATE VIEW register_sums AS (
    SELECT
        customer_id,
        SUM(purchase) AS tot_pur,
        SUM(paid) AS tot_paid,
        SUM(discount) AS tot_disc, 
        SUM(return) AS tot_return,
        SUM(previous_due) AS tot_due,
        SUM(purchase) + SUM(paid) - SUM(discount) - SUM(return) -
            SUM(previous_due) AS final_due
    FROM register
    GROUP BY customer_id
)

相关问题