1. 程式人生 > >Mysql時間範圍分割槽(RANGE COLUMNS方式)

Mysql時間範圍分割槽(RANGE COLUMNS方式)

開始

1、建立測試表

CREATE TABLE `t_test` (
    `id` INT (11),
    `dates` DATETIME 
);  
ALTER TABLE t_test ADD PRIMARY KEY (id);
ALTER TABLE t_test MODIFY id INT AUTO_INCREMENT;

2、建立一個生成測試資料的儲存過程

       我這裡是生成n條2018年的資料(這個生成的時間有bug、我這裡不管了,只是用來測試)

DELIMITER //
CREATE  PROCEDURE `add_vote_memory`(n INT)
BEGIN  
  DECLARE i INT DEFAULT 1;
  DECLARE datess VARCHAR(256);
    WHILE (i <= n ) DO
    -- 隨機時間 這裡生成的都是2018年的
    SELECT   CONCAT(2018,'-',LPAD(FLOOR(1 + (RAND() * 12)),2,0),'-',LPAD(FLOOR(1 + (RAND() * 28)),2,0)) INTO datess;
      INSERT INTO t_test(dates ) VALUES (datess);
            SET i=i+1;
    END WHILE;
END //

3、生成測試資料

-- 呼叫儲存過程 生成500000條
CALL add_vote_memory(500000);

4、建立分割槽表

CREATE TABLE t_range_test (
    id INT,
    dates DATETIME 
)PARTITION BY RANGE COLUMNS ( dates ) (
    -- 第一組小於2018-01-01的
    PARTITION p1 VALUES LESS THAN  ( '20180101' ),
    PARTITION p2 VALUES LESS THAN  ( '20180201' ),
    PARTITION p3 VALUES LESS THAN  ( '20180301' ),
    PARTITION p4 VALUES LESS THAN  ( '20180401' ),
    PARTITION p5 VALUES LESS THAN  ( '20180501' ),
    PARTITION p6 VALUES LESS THAN  ( '20180601' ),
    PARTITION p7 VALUES LESS THAN  ( '20180701' ),
    PARTITION p8 VALUES LESS THAN  ( '20180801' ),
    PARTITION p9 VALUES LESS THAN  ( '20180901' ),
    PARTITION p10 VALUES LESS THAN ( '20181001' ),
    PARTITION p11 VALUES LESS THAN ( '20181101' ),
    PARTITION p12 VALUES LESS THAN ( '20181201' ),
    -- 最後一組小於2019-01-01大於2018-12-01的
    PARTITION p13 VALUES LESS THAN ( '20190101' )
);

5、把上面測試表的資料插入到分割槽表中

INSERT INTO t_range_test SELECT * FROM t_test;

6、檢視執行計劃、結果看PARTITIONS列

EXPLAIN PARTITIONS SELECT * FROM t_range_test WHERE dates >= '20181107124503' AND dates<='20181210111230';

  結果:

7、查看錶分割槽狀況

-- 查詢這個表有多少分割槽
-- 查詢每一個分割槽對應的數量
SELECT t.`PARTITION_NAME`,t.`SUBPARTITION_NAME`,t.`TABLE_ROWS` FROM information_schema.`PARTITIONS` t WHERE t.`TABLE_NAME` = 't_range_test';

8、重新定義表分割槽

-- 給表重新定義分割槽
ALTER TABLE t_range_test PARTITION BY RANGE COLUMNS ( dates ) (
    -- 第一組小於2018-01-01的
    PARTITION p1 VALUES LESS THAN  ( '20180101' ),
    PARTITION p2 VALUES LESS THAN  ( '20180201' ),
    PARTITION p3 VALUES LESS THAN  ( '20180301' ),
    PARTITION p4 VALUES LESS THAN  ( '20180401' ),
    PARTITION p5 VALUES LESS THAN  ( '20180501' ),
    PARTITION p6 VALUES LESS THAN  ( '20180601' ),
    PARTITION p7 VALUES LESS THAN  ( '20180701' ),
    PARTITION p8 VALUES LESS THAN  ( '20180801' ),
    PARTITION p9 VALUES LESS THAN  ( '20180901' ),
    PARTITION p10 VALUES LESS THAN ( '20181001' ),
    PARTITION p11 VALUES LESS THAN ( '20181101' ),
    PARTITION p12 VALUES LESS THAN ( '20181201' ),
    PARTITION p13 VALUES LESS THAN ( '20190101' ),
    -- 最後一組小於2020-01-01大於2019-01-01的
    PARTITION p14 VALUES LESS THAN ( '20200101' )
);

 

結束

 

結尾:僅供自己學習,記錄問題和參考,若有帶來誤解和不便請見諒,共勉!