我有两个名为'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_id的每一列的总和,并自动更新“客户”表的列。 “客户”表如下:
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,因此最好的简便方法可以救我。任何帮助表示赞赏。预先感谢。
答案 0 :(得分:1)
老实说,除非您需要以闪电般的方式利用这些金额,否则我建议您仅将每个交易的值分别存储,然后创建一个按客户汇总并找到金额的视图:
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
)