MySQL 是一款常用的數據庫管理系統,可以在其中創建表格,并根據表格中的某個字段進行分區。其中基于日期的分區,是一個非常常見的應用場景,接下來將介紹如何在 MySQL 中根據日期建分區。
CREATE TABLE my_table ( id INT(11) NOT NULL AUTO_INCREMENT, created_at DATE NOT NULL, PRIMARY KEY(id, created_at) ) ENGINE=InnoDB PARTITION BY RANGE COLUMNS(created_at)( PARTITION p201801 VALUES LESS THAN ('2018-01-01'), PARTITION p201802 VALUES LESS THAN ('2018-02-01'), PARTITION p201803 VALUES LESS THAN ('2018-03-01'), PARTITION p201804 VALUES LESS THAN ('2018-04-01'), PARTITION p201805 VALUES LESS THAN ('2018-05-01'), PARTITION p201806 VALUES LESS THAN ('2018-06-01'), PARTITION p201807 VALUES LESS THAN ('2018-07-01'), PARTITION p201808 VALUES LESS THAN ('2018-08-01'), PARTITION p201809 VALUES LESS THAN ('2018-09-01'), PARTITION p201810 VALUES LESS THAN ('2018-10-01'), PARTITION p201811 VALUES LESS THAN ('2018-11-01'), PARTITION p201812 VALUES LESS THAN ('2018-12-01'), PARTITION p201901 VALUES LESS THAN ('2019-01-01'), PARTITION p201902 VALUES LESS THAN ('2019-02-01'), PARTITION p201903 VALUES LESS THAN ('2019-03-01'), PARTITION p201904 VALUES LESS THAN ('2019-04-01'), PARTITION p201905 VALUES LESS THAN ('2019-05-01'), PARTITION p201906 VALUES LESS THAN ('2019-06-01'), PARTITION p201907 VALUES LESS THAN ('2019-07-01'), PARTITION p201908 VALUES LESS THAN ('2019-08-01'), PARTITION p201909 VALUES LESS THAN ('2019-09-01'), PARTITION p201910 VALUES LESS THAN ('2019-10-01'), PARTITION p201911 VALUES LESS THAN ('2019-11-01'), PARTITION p201912 VALUES LESS THAN ('2019-12-01') );
上述代碼中,我們首先創建了一個名為 my_table 的表格,并指定其中有一個列為 created_at,列的類型為 DATE。然后我們指定了表格的主鍵,即 id 和 created_at。接下來在創建表格時我們使用了 PARTITION BY RANGE COLUMNS 子句,并指定了 created_at 作為 partition 列,即基于 created_at 這一列進行分區,接著通過 VALUES LESS THAN 指定了每個分區的值。在上述代碼中,我們以月份為分區依據。