#!/bin/bash
#按年分区,每年的12月份执行该脚本
table=tablexxx
mysql=/usr/local/mysql/bin/mysql
user=xxx
password=xxxx
#MySQL添加分区的时候,不需要指定字段名称
str_0="alter TABLE $table add partition ("
str_1="PARTITION p"
str_2="VALUES LESS THAN (unix_timestamp('"
str_4=") ENGINE = InnoDB);"
str_3="')"
str_all=''
now_month=`date +%m`
i=1
#按年分区
while [ $i -lt 13 ] #一次添加12个分区
do
month=`date -d "-${i} month ago " +%Y%m` #年月,格式如201607
let j=i+1
day=`date -d "-${j} month ago " +%Y-%m`"-01" #年月日,格式如2016-08-01
str_line="${str_0}$str_1${month} $str_2${day}${str_3}$str_4\n"
#格式如:alter TABLE tablexxx add partition (PARTITION p201607 VALUES LESS THAN (unix_timestamp('2016-08-01')) ENGINE = InnoDB);
# echo $str_line
str_all=$str_all${str_line}
let i=i+1
done
#echo -e $str_all
mysql -u$user -p$password -e "use tmp;CREATE TABLE if not exists tablexxx ( id int(11) NOT NULL AUTO_INCREMENT, ips varchar(50) DEFAULT NULL COMMENT '访客IP', from_linkid int(11) DEFAULT NULL COMMENT '链接的ID号', adddate int(11) DEFAULT NULL COMMENT '访问时间', HTTP_REFERER varchar(300) DEFAULT NULL COMMENT '来源', location_url varchar(255) NOT NULL DEFAULT '' COMMENT '当前url',PRIMARY KEY ( id , adddate ),KEY from_linkid ( from_linkid ),KEY idx_referer ( HTTP_REFERER (255)),KEY idx_adddate ( adddate )) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站联盟-来访IP记录'PARTITION BY RANGE (adddate)( PARTITION p201506 VALUES LESS THAN (unix_timestamp('2015-07-01')), PARTITION p201507 VALUES LESS THAN (unix_timestamp('2015-08-01')), PARTITION p201508 VALUES LESS THAN (unix_timestamp('2015-09-01')));"
mysql -u$user -p$password -e "use tmp;$str_all"