日期:2014-05-16  浏览次数:20735 次

关于mysql按日期分区
表结构
SQL code

CREATE TABLE `p_test` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `beginTime` datetime DEFAULT NULL,
  `data` varchar(32) NULL,
  PRIMARY KEY (`Id`, `beginTime`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1  

PARTITION BY RANGE (TO_DAYS(beginTime)) (
    /*2011*/
    PARTITION p201107 VALUES LESS THAN (TO_DAYS('2011-08-01')),
    PARTITION p201108 VALUES LESS THAN (TO_DAYS('2011-09-01')),
    PARTITION p201109 VALUES LESS THAN (TO_DAYS('2011-10-01')),
    PARTITION p201110 VALUES LESS THAN (TO_DAYS('2011-11-01')),
    PARTITION p201111 VALUES LESS THAN (TO_DAYS('2011-12-01')),
    PARTITION p201112 VALUES LESS THAN (TO_DAYS('2012-01-01')),
);



上面的表按年月,进行了分区
SQL code

EXPLAIN PARTITIONS SELECT * FROM `p_test` WHERE beginTime >= '2011-10-01 00:00:01' AND beginTime < '2011-12-01 00:00:01'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: p_test
   partitions: p201107,p201110,p201111,p201112
         type: range
possible_keys: idx_beginTime
          key: idx_beginTime
      key_len: 8
          ref: NULL
         rows: 4
        Extra: Using where
1 row in set (0.00 sec)


上面的语句,beginTime指定的范围是10到12月,按我的理解,它只扫描p201110, p201111, p201112分区才对,但是实际情况是它还扫描了p201107分区,请问各位这是为什么啊?

------解决方案--------------------
范围扫描时,第一个分区必被扫到。等值扫描就不会。
------解决方案--------------------
因为是范围扫描,查找的时候,肯定要和最小的那个范围进行比较。