我已经创建了一个事件,它将根据余额和插入行的时间,每隔5分钟更新表'try_event‘中的余额。
事件代码:
delimiter $$
CREATE EVENT `event`
ON SCHEDULE every 1 second
DO
begin
-- update balance by 2%
UPDATE try_event
SET Balance = case
WHEN timestampdiff(minute,date_created,current_timestamp) >0 and timestampdiff(minute,date_created,current_timestamp) MOD 5 = 0 and (balance>2000 and balance<3000) then Balance * 1.02
end;
end $$
delimiter ;表:
create table try_event(balance numeric(10,2) not null,date_created timestamp);插入的行数:
insert into try_event values(2500,default);
insert into try_event values(1000,default);但它仍然在5分钟后给出了balance=2500。
当我删除"(balance>2000 and balance<3000)“时,整个balance列都会更新,结果是:
2550
1020发布于 2013-02-17 04:42:28
我刚刚在Percona 5.5.29 (实际上是Percona Server,它是带有一些补丁和新特性的MySQL )的实例上创建了一个测试表。它工作得很好,它更新了2500余额,但没有更新1000余额。
下面的检查显示是否发生了更新(包括自动更新时间戳列):
mysql> SELECT timestampdiff(MINUTE, date_created, current_timestamp) AS td,
balance FROM try_event;
+------+---------+
| td | balance |
+------+---------+
| 8 | 1000 |
| 3 | 2550 |
+------+---------+我对事件定义做了细微的修改:
在使用CASE表达式时,表示" ELSE“子句是值得的,否则如果When条件为false,并且没有ELSE子句,CASE表达式的结果就只是NULL。
UPDATE try_event
SET Balance = CASE
WHEN timestampdiff(minute,date_created,current_timestamp) >0
AND timestampdiff(minute,date_created,current_timestamp) MOD 5 = 0
AND balance>2000 and balance<3000
THEN Balance * 1.02
ELSE Balance -- this is what I added.
END;有没有可能您的balance列被声明为NOT NULL,所以更新试图将balance设置为NULL,但它只是失败了?
我还删除了平衡范围比较周围的圆括号,但这不会有任何区别。
https://stackoverflow.com/questions/14913003
复制相似问题