How to make a foreign key with a constraint on the referenced table in PostgreSQL

后端 未结 3 549
自闭症患者
自闭症患者 2021-01-05 19:59

Suppose I have the following tables

CREATE TABLE plugins (
id int primary key,
type text);

insert into plugins values (1,\'matrix\');
insert into plugins va         


        
3条回答
  •  孤城傲影
    2021-01-05 20:47

    Use a compound key in the referenced table and a CHECK constraint in the referencing table e.g.

    CREATE TABLE plugins (
    id int primary key,
    type text, 
    UNIQUE (type, id)
    );
    
    CREATE TABLE matrix_params (
    id int primary key,
    plugintype text DEFAULT 'matrix' NOT NULL
       CHECK (plugintype = 'matrix'),
    pluginid int NOT NULL,
    FOREIGN KEY (plugintype, pluginid)
       references plugins (type, id)
    );
    

提交回复
热议问题