【專案踩坑】Mysql分割槽:分割槽鍵和唯一索引主鍵的關係,解決報錯 A PRIMARY KEY must include all columns in the table’s partitioning
錯誤:
ERROR 1503 (HY000): A PRIMARY KEY must include all columns in the table’s partitioning
ERROR 1503 (HY000): A UNIQUE INDEX must include all columns in the table’s partitioning function
結論
主鍵必須包括表的分割槽函式中的所有列,一個惟一的索引必須包括表的分割槽函式中的所有列,是不是不太好理解意思?分割槽的key必須是 主鍵!
那就來看看分析
其實就是這麼個意思:表上的每一個唯一性索引必須用於分割槽表的表示式上(其中包括主鍵索引)
下面我來舉幾個例子:
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
PRIMARY KEY (id)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
[Err] 1503 - A PRIMARY KEY must include all columns in the table’s partitioning function
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
UNIQUE KEY (id)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
[Err] 1503 - A PRIMARY KEY must include all columns in the table’s partitioning function
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
PRIMARY KEY (id,bid)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
Query OK, 0 rows affected (0.535 sec)
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
UNIQUE KEY (id,bid)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
Query OK, 0 rows affected (0.625 sec)
這一組例子說明了如果要用bid作為分割槽key,則bid至少要包含在主鍵或者唯一鍵。
再來看一組例子:
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
PRIMARY KEY (id,aid),
UNIQUE KEY (bid)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
[Err] 1503 - A PRIMARY KEY must include all columns in the table’s partitioning function
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
PRIMARY KEY (id,aid),
UNIQUE KEY (bid)
)
PARTITION BY KEY(aid)
PARTITIONS 10;
[Err] 1503 - A PRIMARY KEY must include all columns in the table’s partitioning function
這2個分割槽表是無法建立的,因為沒有一個分割槽鍵,可以同時屬於兩個唯一性索引的鍵。
下面再來看一組例子:
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
PRIMARY KEY (id,aid,bid)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
Query OK, 0 rows affected (0.475 sec)
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
UNIQUE KEY (id,aid,bid)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
Query OK, 0 rows affected (0.532 sec)
SQL
CREATE TABLE t1 (
id INT NOT NULL,
aid DATE NOT NULL,
bid INT NOT NULL,
PRIMARY KEY (id,aid,bid),
UNIQUE KEY (bid)
)
PARTITION BY KEY(bid)
PARTITIONS 10;
Query OK, 0 rows affected (0.526 sec)
這三個都建立分割槽表成功了,因為bid同時屬於一個或以上的唯一性索引的鍵
通過上面這些例子,大家可以深入的理解Mysql分割槽中分割槽鍵和唯一索引主鍵的關係了,
主要是,分割槽的key必須是 主鍵!
禁止 學習某地爬蟲,知乎爬蟲,CSDN 爬蟲。
本文,首發在 learnku 社群。
@author
汪春波(www.shxdledu.cn)
本作品採用《CC 協議》,轉載必須註明作者和本文連結