鍍金池/ 問(wèn)答/C  數(shù)據(jù)庫(kù)/ mysql分區(qū)后查詢總是掃描所有分區(qū)

mysql分區(qū)后查詢總是掃描所有分區(qū)

使用如下sql語(yǔ)句創(chuàng)建表:

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)
);

插入數(shù)據(jù)查看分區(qū)的存儲(chǔ)情況如下:

select partition_name, PARTITION_DESCRIPTION, PARTITION_EXPRESSION, table_rows from information_schema.partitions where table_name = 't'

圖片描述

但是在查詢數(shù)據(jù)時(shí)總是需要查詢所有分區(qū)

explain select * from t where created_at < '2018-04-01';

圖片描述
正常情況下不應(yīng)該只查詢前3個(gè)分區(qū)嗎,為什么在這里會(huì)掃描所有分區(qū)呢?

回答
編輯回答
逗婦惱

emm...我測(cè)試過(guò),V5.6,mod沒(méi)問(wèn)題,但是月份是不行。如第1樓的回答。

處理方式是:?jiǎn)为?dú)加字段保存月份,用這個(gè)月份字段做分區(qū),查詢加條件就可以。

2018年8月7日 01:37
編輯回答
九年囚

根據(jù)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不可以。

2018年1月24日 07:27
編輯回答
孤慣

這個(gè)應(yīng)該是跟分區(qū)類型有關(guān)吧。印象中根據(jù)ID進(jìn)行分區(qū)的時(shí)候不會(huì)全部掃描所有分區(qū)。記憶不是很清了,可以參考mysql官方文檔。

2017年8月23日 00:11