我的数据库中有一个名为 stockpricehistory 的表,它跟踪库存商品的价格变化,并包含以下字段:
- 股票 ID
- 价格
- 开始日期(该特定价格推出的时间)
- DateEnd(当该特定价格停止使用时)。
DateStart 默认为 CURRENT_TIMESTAMP,DateEnd 默认为空,就好像没有 DateEnd 值一样,那么该行中的价格就是该库存商品的当前价格。
现在,我怎样才能(我假设是通过触发器)做到这一点,以便每当我为特定库存商品插入新行时,它都会更新该库存商品的最后一个当前行(即匹配的行)该库存项目(其中 DateEnd 设置为 NULL)以匹配刚刚为要插入的新行指定的 DateStart 值,如下所示:
这是表的初始状态:
- 1,2.99,2013-11-19 18:49:24,NULL
然后,当为该库存商品(ID 1)插入新行时,结果如下:
1,4.99,2013-11-20 12:00:00,NULL
1,2.99,2013-11-19 18:49:24,2013-11-20 12:00:00
理论上,它应该只需要更新一行,因为每个股票 ID 只有一行没有结束日期,即包含当前价格的行。
我认为这将通过 BEFORE INSERT 触发器完成,但我很可能是错的。
最佳答案
正如 @Filipe Silva 所说,您无法在该表上调用的触发器中修改该表。
您可以通过为股票和股价历史记录单独的表来解决这个问题,这在任何情况下都是一个好主意。 stock
表为每个库存商品保存一行及其当前价格,并且该表上的触发器将 stockpricehistory
中的记录维护为 stock
中的行> 被插入或更新。
http://sqlfiddle.com/#!2/55c626/1
create table stock (
stockId int primary key,
price numeric(5, 2));
create table stockpricehistory (
stockId int,
price numeric(5,2),
dateStart datetime,
dateEnd datetime);
create trigger t_si before insert on stock
for each row
insert into stockpricehistory values (new.stockId, new.price, current_timestamp, null);
create trigger t_su before update on stock
for each row begin
update
stockpricehistory
set
dateEnd = current_timestamp
where
stockId = new.stockId and
dateEnd is null;
insert into stockpricehistory values (new.stockId, new.price, current_timestamp, null);
end;
关于mysql - 如何编写一个触发器,在提交插入之前更新同一个表中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079686/