简体   繁体   English

MySQL触发器。 如何在有限的时间内存储表中的每一行数据?

[英]MySQL trigger. How to store each row of data in table for a limited time?

There is a table in my database every row of which should be stored for a limited time (1 minute). 我的数据库中有一个表,该表的每一行都应存储有限的时间(1分钟)。 I'm trying to do the ON INSERT trigger like this: 我正在尝试像这样执行ON INSERT触发器:

CREATE TRIGGER `temp_data_trig` AFTER INSERT ON `tokens`
FOR EACH ROW 
BEGIN
    DO SLEEP(60);
    DELETE FROM `tokens` WHERE id = NEW.id;
END

But when i'm trying to insert a new row i'm getting this: 但是,当我尝试插入新行时,我得到了:

Can't update table 'tokens' in stored function/trigger because it is 
already used by statement which invoked this stored function/trigger.

What is wrong with my trigger and what is the right way to store each row of data for a limited time? 我的触发器出了什么问题?在有限的时间内存储每一行​​数据的正确方法是什么?

In general, you don't want to do sleep in a trigger. 通常,您不想在触发器中sleep That just locks the table. 那只是锁住桌子。

I would suggest that you take one of the following approaches. 我建议您采用以下方法之一。

The first is to include the date/time stamp when something is inserted. 第一种是在插入某些内容时包括日期/时间戳。 Then have a job that goes through an deletes records more than a minute old. 然后有一个要经过删除记录的工作已有一分钟多的时间。 Do note that this puts a fair amount of load on the database. 请注意,这给数据库带来了相当大的负载。 Alternatively, you could just keep all the records, inserting them at will, and have a view that selects the ones created in the last minute: 或者,您可以保留所有记录,随意插入它们,并具有一个视图来选择在最后一分钟创建的记录:

create view v_table
    select *
    from table
    where createdat >= now() - interval 1 minute;

The final solution is to partition the data by minute intervals. 最终的解决方案是按分钟间隔对数据进行分区。 Then you can drop partitions with minimal impact on the performance of the database ("minimal" relative to other options that might lock the table for longer periods of time). 然后,您可以删除对数据库性能影响最小的分区(相对于其他可能将表锁定较长时间的选项,“最小”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM