簡體   English   中英

postgresql 通過外鍵傳遞唯一約束

[英]postgresql transitive unique constraints via foreign key

我有以下架構:

CREATE TABLE t2 (
    id TEXT PRIMARY KEY,

    t1_id TEXT REFERENCES t1(id)
);

CREATE TABLE t3 (
    id TEXT PRIMARY KEY,

    t2_id TEXT REFERENCES t2(id)
);

CREATE TABLE t4 (
    t4_counter BIGINT NOT NULL,

    t3_id TEXT REFERENCES t3(id),

    // Need UNIQUE constraint on t4_counter + t2_id
);

我們的系統中有 3 個 postgresql 表(t2、t3、t4)。 還有其他表格,但為簡潔起見,它們被忽略。 現在 t2 有一個 UNIQUE id,它在 t3 中被稱為外鍵。 類似地,t3 有一個 UNIQUE id,在 t4 中被引用為 FOREIGN KEY。 現在在 t4 中有一個名為t4_counter的字段。 現在我想在這個表 t4 上應用一個 UNIQUE 約束,這樣, t4_counter combined with t2_id will always be UNIQUE

實現此目的的一種簡單方法是在表 t4 中插入t2_id作為具有REFERENCES約束的新列,然后UNIQUE constraint on (t2_id, t4_counter)添加UNIQUE constraint on (t2_id, t4_counter) 但是由於我們已經在表 t4 中有 t3_id ,我們應該能夠傳遞計算它。

是否可以在表 t4 中不添加 t2_id 的情況下實現這樣的唯一約束?

如果重要的話,我正在使用 postgresql 12+ 版本。

您需要將列 t2_id 添加為“冗余”,如@jindra 所述,以強制執行此關系。 您還可以對表 t4 使用復合鍵。 這將永遠解決數據庫級別的問題。

例如:

create table t3 (
  id int not null,
  t2_id int not null references t2(id),
  primary key (id, t2_id) -- composite primary key
);

create table t4 (
  t4_counter bigint not null,

  t3_id int not null,
  t2_id int not null,
  constraint fk1 foreign key (t3_id, t2_id) references t3 (id, t2_id),

  constraint uq1 unique (t2_counter, t2_id)
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM