我认为最好的方式是扳机?有什么想法吗?
对于表付款中的每个用户名,我应该分别向payment_amount
表 total_balance 中插入total_money
的总和,每次自动插入当表 Payments
例如: 用户“ John”用2次100 $和50 $填充了他的帐户,帐户中的总计150 $
表格示例:
表格:付款
ID username payment_amount Status
+-------+-------------+-------------+-----------+
| 1 | John | 100 | Complete |
+-------+-------------+-------------+-----------+
| 2 | John | 50 | Complete |
+-------+-------------+-------------+-----------+
| 3 | Alex | 100 | Complete |
+-------+-------------+-------------+-----------+
表格:总余额
ID username total_money
+-------+-------------+-------------+
| 1 | John | 150 |
+-------+-------------+-------------+
| 2 | Alex | 100 |
+-------+-------------+-------------+
答案 0 :(得分:1)
我建议不要保留冗余数据。当出现不一致时,这很可能会导致灾难。我建议您使用一个视图,它可以为您提供总和。
DROP TABLE total_balance;
CREATE VIEW total_balance
AS
SELECT p.username,
sum(p.payment_amount) total_money
FROM payments p
GROUP BY p.username;
或者,如果您只想对已完成的付款进行总计:
DROP TABLE total_balance;
CREATE VIEW total_balance
AS
SELECT p.username,
sum(p.payment_amount) total_money
FROM payments p
WHERE p.status = 'Complete'
GROUP BY p.username;
视图中的数字将始终准确无误,并能反映当前情况。