知识屋:更实用的电脑技术知识网站
所在位置:首页 > 站长园地  > 站长入门

MySQL定期自动删除表

发表时间:2015-05-30来源:网络

单位8亿多条的日志表,经过自动分表之后,需要自动删除30天前创建的日志表。
但是只是在Master下线这些日志表,而Slave还需要保持在线,以备查询。
由于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 rows in set (0.00 sec)

    过程如下:

    delimiter $$

    CREATE procedure drop_table()

    BEGIN

    declare t_name varchar(64);

    declare isFinished int default false;

    declare log_table_list cursor for (select table_name from information_schema.tables where table_schema ='EDMOND' and table_name like'sod_song_log_%');

    declare continue handler for not found set isFinished=true;

    open log_table_list;

    repeat

    fetch log_table_list into t_name;

    if isFinished = false then

    if datediff(now(),replace(t_name,'sod_song_log_',''))>30 then

    set @@session.sql_log_bin=0;

    set @sqltext=concat('drop table ',t_name,';');

    PREPARE c_tab_stat from @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 row in set (0.00 sec)

      mysql> select now() from dual;

      +---------------------+

      | now() |

      +---------------------+

      | 2014-04-22 17:58:24 |

      +---------------------+

      1 row in set (0.00 sec)

        并且binlog中没有记录这个Drop的行为。
            配合Linux crontab即可实现定期自动删除表的功能。
            一定不要把sql_log_bin设置为global级别,不能犯迷糊

        (免责声明:文章内容如涉及作品内容、版权和其它问题,请及时与我们联系,我们将在第一时间删除内容,文章内容仅供参考)
        收藏
        • 人气文章
        • 最新文章
        • 下载排行榜
        • 热门排行榜