Mysql

兩個外鍵約束最方便的索引策略是什麼?

  • December 7, 2021

以下兩個選項中哪個更方便索引相關外鍵?

選項 A

Create Table table3(
 t3_id int not null auto_increment,
 t1_id int not null,
 t2_id int not null,
 primary key (t3_id),
 index IX_index (t1_id, t2_id), // this is my concern
 constraint FK_t1 foreign key (t1_id)
 reference table1(t1_id),
 constraint FK_t2 foreign key (t2_id)
 reference table2(t2_id));

選項 B:

Create Table table3(
 t3_id int not null auto_increment,
 t1_id int not null,
 t2_id int not null,
 primary key (t3_id),
 index IX_t1 (t1_id), //this is my concern
 index IX_t2 (t2_id), //and this
 constraint FK_t1 foreign key (t1_id)
 reference table1(t1_id),
 constraint FK_t2 foreign key (t2_id)
 reference table2(t2_id));

我正在使用InnoDB我對btree索引的工作原理沒有廣泛的了解,但據我所知,第一個表會將索引保存在單個區域,而第二個不會(如果我錯了,請糾正我)。

定義單列或多列索引的優缺點什麼?

創建表腳本 2 是正確的。

InnoDB 需要外鍵和引用鍵上的索引,以便外鍵檢查可以快速且不需要表掃描。在引用表中,必須有一個索引,其中外鍵列按相同順序列為第一列。如果引用表不存在,則會在引用表上自動創建此類索引。(這與一些舊版本形成對比,在這些舊版本中,索引必須顯式創建,否則外鍵約束的創建將失敗。) index_name,如果給定,如前所述使用。

如果這是一個簡單的多:多映射表,我建議丟棄大部分列。這AUTO_INCREMENT是一種浪費,甚至會減慢處理速度。相反,您需要兩個 2 列索引,其中一個是PRIMARY KEY,另一個是普通索引。在我看來,FK 的添加不足以保證額外的成本。

更多提示在這裡

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