使用如下sql语句创建表:
create table t(
name varchar(20) not null,
age tinyint unsigned,
created_at datetime
) partition by range(month(created_at))(
partition p1 values less than(2),
partition p2 values less than(3),
partition p3 values less than(4),
partition p4 values less than(5),
partition p5 values less than(6),
partition p6 values less than(7),
partition p7 values less than(8),
partition p8 values less than(9),
partition p9 values less than(10),
partition p10 values less than(11),
partition p11 values less than(12),
partition p12 values less than(13)
);
插入数据查看分区的存储情况如下:
select partition_name, PARTITION_DESCRIPTION, PARTITION_EXPRESSION, table_rows from information_schema.partitions where table_name = 't'
但是在查询数据时总是需要查询所有分区
explain select * from t where created_at < '2018-04-01';
正常情况下不应该只查询前3个分区吗,为什么在这里会扫描所有分区呢?
根据mysql文档:This type of optimization can be applied whenever the partitioning expression consists of an equality or a range which can be reduced to a set of equalities, or when the partitioning expression represents an increasing or decreasing relationship. Pruning can also be applied for tables partitioned on a DATE or DATETIME column when the partitioning expression uses the YEAR() or TO_DAYS() function. In addition, in MySQL 5.7, pruning can be applied for such tables when the partitioning expression uses the TO_SECONDS() function.
month() function不可以。