MySQL定期自动删除表
单位8亿多条的日志表,经过自动分表之后,需要自动删除30天前创建的日志表。但是只是在Master下线这些日志表,而Slave还需要保持在线,以备查询。http://blog.itpub.net/29254281/viewspace-1141985/由于Master-Slave结构,在Drop表之前,设置@@session.sql_log_bin=0,那么Drop的行为就没有记录到binlog,所以Slave的日志表就会被保留。模拟环境如下,
-
MySQL> show tables;
-
+---------------------------------+
-
| Tables_in_edmond|
-
+---------------------------------+
-
| sod_song_log_2014_1_22_13_18_20|
-
| sod_song_log_2014_2_22_13_18_20|
-
| sod_song_log_2014_3_22_13_18_20|
-
| sod_song_log_2014_4_22_13_18_20|
-
+---------------------------------+
-
4 rowsin set (0.00 sec)
过程如下:
-
delimiter $$
-
CREATE procedure drop_table()
-
BEGIN
-
declare t_namevarchar(64);
-
declare isFinishedint default false;
-
declare log_table_list cursorfor (select table_namefrom information_schema.tableswhere table_schema='EDMOND' and table_namelike'sod_song_log_%');
-
declare continue handlerfor not foundset isFinished=true;
-
open log_table_list;
-
repeat
-
fetch log_table_listinto t_name;
-
if isFinished= falsethen
-
ifdatediff(now(),replace(t_name,'sod_song_log_',''))>30then
-
set @@session.sql_log_bin=0;
-
set @sqltext=concat('drop table ',t_name,';');
-
PREPARE c_tab_statfrom @sqltext;
-
execute c_tab_stat;
-
set @@session.sql_log_bin=1;
-
end if;
-
end if;
-
until isFinished
-
end repeat;
-
close log_table_list;
-
END $$
-
delimiter;
执行过程,结果如下
-
mysql> call drop_table();
-
Query OK, 0 rows affected(0.28 sec)
-
-
mysql> show tables;
-
+---------------------------------+
-
| Tables_in_edmond|
-
+---------------------------------+
-
| sod_song_log_2014_4_22_13_18_20|
-
+---------------------------------+
-
1 rowin set (0.00 sec)
-
-
mysql> select now() from dual;
-
+---------------------+
-
| now() |
-
+---------------------+
-
| 2014-04-22 17:58:24|
-
+---------------------+
-
1 rowin set (0.00 sec)
并且binlog中没有记录这个Drop的行为。
配合Linux crontab即可实现定期自动删除表的功能。
一定不要把sql_log_bin设置为global级别,不能犯迷糊
网页标题:MySQL定期自动删除表
分享URL:
http://jkwzsj.com/article/jgcogj.html