stored procedures - Delete all but 5 newest entries in MySQL table -


i have php code handles logic because not know how handle in sql. want create stored procedure delete rows except 5 newest given config_id. ie config_id = 5 gets passed sp knows config_id looking clean up.

create table  `taa`.`runhistory` (   `id` int(11) not null auto_increment,   `start_time` datetime default null,   `stop_time` datetime default null,   `success_lines` int(11) default null,   `error_lines` int(11) default null,   `config_id` int(11) not null,   `file_id` int(11) not null,   `notes` text not null,   `log_file` longblob,   `save` tinyint(1) not null default '0',   primary key  (`id`) ) engine=innodb auto_increment=128 default charset=utf8; 

newest determined start_time, if stop_time null not newest should deleted (stop_time can null if run unceremoniously killed).

here's procedure tested on mysql 5.1.46, uses no subqueries won't error no support limit in subquery.

create procedure deletebut5(in c int) begin   declare int;   declare s datetime;    select id, stop_time i, s   runhistory config_id = c   order stop_time desc, id desc   limit 4, 1;    delete runhistory stop_time < s or stop_time = s , id < i; end 

i recommend create covering index:

create index cov on runhistory (config_id, stop_time, id); 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -