mysql event

阅读更多

 

fdate按日期分区

create table myevent
(
	fdate int(11) not null default '0',
	appid int,
	primary key(fdate)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY RANGE(TO_DAYS(fdate))
(PARTITION p20190217 VALUES LESS THAN (TO_DAYS('2019-02-17')) ENGINE = InnoDB,
PARTITION p20190218 VALUES LESS THAN (TO_DAYS('2019-02-18')) ENGINE = InnoDB);

 如果fdate非date类型,会报错:

 1486 - Constant, random or timezone-dependent expressions in (sub)partitioning function are not allowed

 

添加或删除分区 

ALTER TABLE myevent ADD PARTITION (PARTITION p20190219 VALUES LESS THAN (TO_DAYS('20190219')));
ALTER TABLE myevent DROP PARTITION p20190219;

 

查看使用分区数

explain PARTITIONS select * from myevent;

+----+-------------+---------+-------------------------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table   | partitions                    | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
+----+-------------+---------+-------------------------------+------+---------------+------+---------+------+------+----------+-------+
|  1 | SIMPLE      | myevent | p20190217,p20190218,p20190219 | ALL  | NULL          | NULL | NULL    | NULL |    1 |      100 | NULL  |
+----+-------------+---------+-------------------------------+------+---------------+------+---------+------+------+----------+-------+

 

判断分区是否存在:

SELECT count(1) from INFORMATION_SCHEMA.partitions WHERE TABLE_SCHEMA = schema() 
AND TABLE_NAME='myevent' AND partition_name='p20190220';

   

 

上述分区需要预配置,可以用event来实现每天自动创建分区。

开启event

SHOW VARIABLES LIKE '%event_sche%';
SET GLOBAL event_scheduler = 1;

  

创建定时任务

DROP EVENT if exists myevent_auto_partition;
DELIMITER  $$
CREATE EVENT myevent_auto_partition
ON SCHEDULE 
    EVERY 1 DAY
    STARTS '2019-03-01 00:00:00'
    COMMENT '天表每天自动增加分区'
   DO
BEGIN
set @c_table='myevent';
set @c_day=curdate();
set @p_c_day=DATE_FORMAT(NOW(), '%Y%m%d');
set @p_name=concat('p', @p_c_day);
set @p_sql=concat('ALTER TABLE ', @c_table,' ADD PARTITION (PARTITION ', @p_name,' VALUES LESS THAN (TO_DAYS ("', @c_day, '")))');
SELECT @p_sql;
PREPARE stmt from @p_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END  $$
DELIMITER ;

 

查看计划任务

show events;

drop event if exists myevent_auto_partition;

 

查询所有事件sql

select * from mysql.event;

 

 

 

 

 

 

 

 

你可能感兴趣的:(partition,event)