我的财务系统(php / mysql)有下表,超过5000条记录。所有余额字段均为空。
+---------+------+---------------------+---------+
| amount | done | date | balance |
+---------+------+---------------------+---------+
| 44.00 | 1 | 2018-02-13 14:23:32 | 0.00 |
+---------+------+---------------------+---------+
| 1000.00 | 0 | 2018-02-14 18:13:05 | 0.00 |
+---------+------+---------------------+---------+
| 500.00 | 1 | 2018-02-16 15:20:00 | 0.00 |
+---------+------+---------------------+---------+
| -40.00 | 1 | 2018-02-14 17:30:00 | 0.00 |
+---------+------+---------------------+---------+
当用户将“已完成”字段编辑为1时,我需要更新余额字段,以获取上次付款的金额(基于日期字段)。
+---------+------+---------------------+---------+
| amount | done | date | balance |
+---------+------+---------------------+---------+
| 44.00 | 1 | 2018-02-13 14:23:32 | 44.00 |
+---------+------+---------------------+---------+
| 1000.00 | 0 | 2018-02-14 18:13:05 | 0.00 |
+---------+------+---------------------+---------+
| 500.00 | 1 | 2018-02-16 15:20:00 | 544.00 |
+---------+------+---------------------+---------+
| -40.00 | 1 | 2018-02-14 17:30:00 | 4.00 |
+---------+------+---------------------+---------+
我可以很容易地触发它,但是我无法弄清楚如何在编辑行的日期最早时更新已经完成的付款余额(mysql不允许在更新上下文中运行更新触发器)。
假设用户编辑第二行,第三,第四和所有后续行的余额也将更新:
+---------+------+---------------------+---------+
| amount | done | date | balance |
+---------+------+---------------------+---------+
| 44.00 | 1 | 2018-02-13 14:23:32 | 44.00 |
+---------+------+---------------------+---------+
| 1000.00 | 1 | 2018-02-14 18:13:05 | 1004.00 |
+---------+------+---------------------+---------+
| 500.00 | 1 | 2018-02-16 15:20:00 | 1544.00 |
+---------+------+---------------------+---------+
| -40.00 | 1 | 2018-02-14 17:30:00 | 04.00 |
+---------+------+---------------------+---------+
我怎么做?
答案 0 :(得分:1)
我解决了将此表拆分为新表的问题(如@Solarflare建议),在表1中维护原始触发器并运行表2中的以下函数:
DELIMITER $$
CREATE PROCEDURE `updateBalance`(IN `date_input` DATETIME)
NO SQL
BEGIN
set @csum = 0;
UPDATE transactions
set balance = (@csum := @csum + amount)
where date > date_input
order by date asc;
END$$
DELIMITER ;