MySQL 大表數據按期歸檔

數據庫有一張表數據量很大,真正WEB項目只用到一個月內的數據,所以把一個月前的舊數據按期歸檔。數據庫

 

1 - 建立一個新表,表結構和索引與舊錶如出一轍線程

create table table_news like table_name;rest

 

2 - 新建存儲過程,查詢30天的數據並歸檔進新數據庫,而後把30天前的舊數據從舊錶裏刪除orm

delimiter $
create procedure sp()
begin
insert into tb_new select * from table_namewhere create_time < NOW()  -  INTERVAL 30 DAY;
delete from db_smc.table_namewhere create_time < NOW() - INTERVAL 30 DAY;
end索引

 

3 - 建立EVENT,天天晚上凌晨00:00定時執行上面的存儲過程進程

create event if not exists event_temp 
on schedule every 1 day
on completion preserve
do call sp();ssl

 

備註:it

第一次執行存儲過程的時候由於歷史數據過大, 可能發生意外讓該次執行沒有成功。從新執行時會遇到報錯ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction,應急解決方案以下:io

一、執行show full processlist;查看全部MySQL線程event

二、執行SELECT * FROM information_schema.INNODB_TRX\G; 查看是否有錯誤線程,線程id在show full processlist;的結果中狀態爲sleep

三、kill 進程id

相關文章
相關標籤/搜索