Postgresql

Postgres:複合類型組件的外鍵約束?

  • December 13, 2019

在 Postgres 中,是否可以在如下情況下設置涉及復合類型組件的外鍵約束?

假設我有

CREATE TABLE main (
   -- a and b are separate fields
   a INTEGER,
   b INTEGER,
   PRIMARY KEY (a,b)
);
CREATE TYPE abtype AS (
   a INTEGER,
   b INTEGER
);
CREATE TABLE sub (
   -- a and b are components of a composite type
   ab abtype,
   PRIMARY KEY (ab)
);

如何設置指定sub.ab引用的外鍵約束main.(a,b)

以下嘗試在語法上都是錯誤的。

ALTER TABLE sub ADD CONSTRAINT sub_ab_fkey FOREIGN KEY
... (ab) REFERENCES main(a,b);
... (ab) REFERENCES main((a,b));   
... (ab) REFERENCES main((a,b)::abtype);
... (ab) REFERENCES main(a,b)::abtype;
... ((ab).a,(ab).b) REFERENCES main(a,b);
... (ab.a,ab.b) REFERENCES main(a,b);

正如我在評論中指出的那樣,您可以在表中添加一個新的複合列main

CREATE TYPE abtype AS (
   a INTEGER,
   b INTEGER
);

CREATE TABLE main (
   -- a and b are separate fields
   a INTEGER,
   b INTEGER,
   ab abtype generated always as ((a,b)) stored,
   PRIMARY KEY (a,b)
);

CREATE TABLE sub (
   -- a and b are components of a composite type
   ab abtype,
   PRIMARY KEY (ab)
);

並設置唯一索引:

create unique index on main (ab);

現在您可以將您的 FK 引用到此列:

ALTER TABLE sub ADD CONSTRAINT sub_ab_fkey FOREIGN KEY (ab) references main(ab);

db<>在這裡擺弄

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