Partitioning

在 MySql 5.7 中使用主鍵和唯一鍵進行分區

  • February 15, 2021

我正在嘗試在 MySQL 5.7 AWS RDS 中創建一個雜湊分區,因為該表在一個月內增長得非常快,大約有 2 億行。表結構是這樣的,並嘗試創建如下分區

 itemid bigint(20) NOT NULL AUTO_INCREMENT,
 ownerid int(11) NOT NULL,
 product_id int(11) NOT NULL,
 creation_time datetime DEFAULT NULL,
 used_time datetime DEFAULT NULL,
 ......
 ......
 ......
 ......
 PRIMARY KEY (itemid),
 UNIQUE KEY owner_product_uidx (ownerid,product_id),
 KEY prod_indx (product_id)
) 
PARTITION BY HASH(itemid,ownerid,product_id)
PARTITIONS 5;
ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

拋出錯誤 錯誤程式碼:1503。主鍵必須包括表的分區函式中的所有列。

嘗試使用 Partition KEY 而不是 HASH

PARTITION BY key(item_id,owner_id,product_id,creation_time; 

仍然沒有運氣。有沒有人成功創建分區,我也可以用 year(creation_time)-month(creation_time) 作為分區鍵。像(2021-01,2021-02….等)

參考:https ://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations-partitioning-keys-unique-keys.html 有人可以幫忙。

分區有很多限制你不能用多列的HASH

如果您想要多個列,它們必須在主鍵中,如範例中所示。對於您的時間,您可以在第二個範例中看到。你必須做出更多的犧牲,如果那是你所追求的,你必須去測試它。

CREATE TABLE abc
 (
  itemid bigint(20) NOT NULL AUTO_INCREMENT,
  ownerid int(11) NOT NULL,
  product_id int(11) NOT NULL,
  creation_time datetime DEFAULT NULL,
  yearmonth VARCHAR(20) GENERATED ALWAYS AS (CONCAT(YEAR(creation_time),'-',MONTH(creation_time))),
  used_time datetime DEFAULT NULL,
  PRIMARY KEY (itemid,ownerid,product_id),
  UNIQUE KEY owner_product_uidx (itemid,ownerid,product_id),
  KEY prod_indx (product_id)
) ENGINE=INNODB
PARTITION BY KEY(itemid,ownerid,product_id)
 PARTITIONS 5;
CREATE TABLE abc2
 (
  itemid bigint(20) NOT NULL AUTO_INCREMENT,
  ownerid int(11) NOT NULL,
  product_id int(11) NOT NULL,
  creation_time datetime NOT NULL,
  month_ tinyint NOT NULL,
  used_time datetime DEFAULT NULL,
  PRIMARY KEY (itemid,creation_time,month_),
  UNIQUE KEY owner_product_uidx (itemid,creation_time,month_),
  KEY prod_indx (product_id)
) ENGINE=INNODB
PARTITION BY RANGE (YEAR(`creation_time`))
SUBPARTITION BY KEY (month_) 
SUBPARTITIONS 12 (
    PARTITION p2011 VALUES LESS THAN (2012),
    PARTITION p2012 VALUES LESS THAN (2013),
    PARTITION p2013 VALUES LESS THAN (2014),
    PARTITION p2014 VALUES LESS THAN (2015),
    PARTITION p2015 VALUES LESS THAN (2016),
    PARTITION p2016 VALUES LESS THAN (2017),
    PARTITION p2017 VALUES LESS THAN (2018),
    PARTITION p2018 VALUES LESS THAN (2019),
    PARTITION p2019 VALUES LESS THAN (2020),
    PARTITION p2020 VALUES LESS THAN (2021),
    PARTITION pmax VALUES LESS THAN MAXVALUE
);

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/285452