我們有一個分布式/分片資料庫,所以我們使用id和partner_id(這是我們的磁區 ID)的組合作為我們任何分布式表的主鍵。
在我的schema.rb檔案中,此宣告如下所示:
create_table "back_in_stock_subscriptions", primary_key: ["id", "partner_id"], force: :cascade do |t|
導致我的問題的問題是,當我的一位同事運行遷移時,架構被修改為如下所示:
create_table "back_in_stock_subscriptions", primary_key: ["partner_id", "id"], force: :cascade do |t|
因此,無論何時他們運行遷移,他們都必須準備提交他們實際添加到資料庫中的部分,然后丟棄對schema.rb檔案的剩余更改。或者,如果他們正在運行其他人添加的遷移,他們只是schema.rb完全放棄更改。當然,這是一個非常小的麻煩,我不知道為什么會發生這種情況,但它有點令人擔憂。
所以我的問題是它甚至重要嗎?如果他不小心讓其中一個“逆轉”滑入提交中,這會不會很重要(除了下次我運行遷移時,它會逆轉它)?
uj5u.com熱心網友回復:
就唯一性而言,主鍵定義中列的順序無關緊要。
但是主鍵始終使用唯一索引來實作,并且該索引可用于加快查詢速度。為此,列的順序很重要。例如,這個查詢:
SELECT * FROM tab WHERE col1 = 42;
可以使用主鍵(col1, col2)索引,但不能使用主鍵索引(col2, col1)。
uj5u.com熱心網友回復:
一個測驗用例:
create table pk_test1 (id integer, id2 integer, primary key(id, id2));
create table pk_test1 (id integer, id2 integer, primary key(id2, id));
\d pk_test
Table "public.pk_test"
Column | Type | Collation | Nullable | Default
-------- --------- ----------- ---------- ---------
id | integer | | not null |
id2 | integer | | not null |
Indexes:
"pk_test_pkey" PRIMARY KEY, btree (id, id2)
\d pk_test2
Table "public.pk_test2"
Column | Type | Collation | Nullable | Default
-------- --------- ----------- ---------- ---------
id | integer | | not null |
id2 | integer | | not null |
Indexes:
"pk_test2_pkey" PRIMARY KEY, btree (id2, id)
insert into pk_test values (1, 2), (2,1);
insert into pk_test2 values (1, 2), (2,1);
select * from pk_test;
id | id2
---- -----
1 | 2
2 | 1
(2 rows)
test(5432)=# select * from pk_test2;
id | id2
---- -----
1 | 2
2 | 1
insert into pk_test values (1, 2);
ERROR: duplicate key value violates unique constraint "pk_test_pkey"
DETAIL: Key (id, id2)=(1, 2) already exists.
insert into pk_test2 values (1, 2);
ERROR: duplicate key value violates unique constraint "pk_test2_pkey"
DETAIL: Key (id2, id)=(2, 1) already exists.
--THE PROBLEM
create table pk_child_tbl (child_id integer, parent_id integer, parent_id2 integer, foreign key(parent_id, parent_id2) references pk_test2);
insert into pk_test2 values (3,2);
select * from pk_test2;
id | id2
---- -----
1 | 2
2 | 1
3 | 2
\d pk_test2
Table "public.pk_test2"
Column | Type | Collation | Nullable | Default
-------- --------- ----------- ---------- ---------
id | integer | | not null |
id2 | integer | | not null |
Indexes:
"pk_test2_pkey" PRIMARY KEY, btree (id2, id)
Referenced by:
TABLE "pk_child_tbl" CONSTRAINT "pk_child_tbl_parent_id_parent_id2_fkey" FOREIGN KEY (parent_id, parent_id2) REFERENCES pk_test2(id2, id)
insert into pk_child_tbl values (2, 3, 2);
ERROR: insert or update on table "pk_child_tbl" violates foreign key constraint "pk_child_tbl_parent_id_parent_id2_fkey"
DETAIL: Key (parent_id, parent_id2)=(3, 2) is not present in table "pk_test2".
如果您有僅指向父表的外鍵參考,而沒有指定將獲取主鍵順序的父表列順序,并且子 parent_id/parent_id2 欄位將不再匹配父表 id/id2 順序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433915.html
