RDS有一个数据库表tbl_online表,有6千万数据,需要清理,保留3个月。
步骤如下:
- 创建月表
- 将需要删除的数据写入月表
- 删除数据
- 优化表
shell如下:
#!/bin/bash
base="rdsxx.mysql.rds.aliyuncs.com"
#前3个月的日期
months_ago=`date -d "-3 month" +"%Y-%m-%d"`
#前3个月的月份,去掉前面的0
months_ago_mon=`date -d "-3 month" +"%-m"`
#前3个月年份
years_ago_year=`date -d "-3 month" +"%-Y"`
#+++++++++++++++++++++++++++++++++++++
statime=`date +%Y-%m-%d" "%H:%M:%S`
echo "############################" >> /opt/tbl_online.log
#创建月表
/usr/local/mysql/bin/mysql -u root -h $base -e "use kd_shop;create table if not exists tbl_online_bak_"$years_ago_year"_$months_ago_mon like tbl_online;"
echo "$statime开始插入"$months_ago"数据" >> /opt/tbl_online.log
/usr/local/mysql/bin/mysql -u root -h $base -e "use kd_shop;insert into tbl_online_bak_"$years_ago_year"_$months_ago_mon select * from tbl_online where create_time >= ‘$months_ago 00:00:00‘ and create_time <= ‘$months_ago 23:59:59‘;"
statime=`date +%Y-%m-%d" "%H:%M:%S`
echo "$statime插入数据完成" >> /opt/tbl_online.log
#++++++++++++++++++++++++++++++++++++++
statime=`date +%Y-%m-%d" "%H:%M:%S`
echo "$statime开始删除数据以及优化表" >> /opt/tbl_online.log
/usr/local/mysql/bin/mysql -u root -h $base -e "use kd_shop;delete from tbl_online where create_time >= ‘$months_ago 00:00:00‘ and create_time <= ‘$months_ago 23:59:59‘;optimize table tbl_online;"
statime=`date +%Y-%m-%d" "%H:%M:%S`
echo "$statime删除以及优化表完成" >> /opt/tbl_online.log
最后任务计划条用即可