gpt4 book ai didi

php - 如何在mysql中插入一个表的列的SUM作为另一个表的列的值?

转载 作者:行者123 更新时间:2023-11-29 07:26:36 24 4
gpt4 key购买 nike

我有两个名为'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 计算每列的 SUM 并自动更新“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,所以最好和最简单的方法可以拯救我。任何帮助表示赞赏。提前致谢。

最佳答案

老实说,除非您需要以闪电般的速度使用这些总和,否则我可能建议只单独存储每笔交易的值(value),然后创建一个按客户聚合并找到总和的 View :

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
)

关于php - 如何在mysql中插入一个表的列的SUM作为另一个表的列的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53361221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com