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

为君一笑 提交于 2019-12-01 03:56:42

问题


Suppose I have the following tables

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

insert into plugins values (1,'matrix');
insert into plugins values (2,'matrix');
insert into plugins values (3,'function');
insert into plugins values (4,'function');

CREATE TABLE matrix_params (
id int primary key,
pluginid int references plugins (id)
);

This all works as expected but I would like to add an additional constraint that a matrix_param can only refer to the pluginid that has type 'matrix'. So

insert into matrix_params values (1,1);

Should succeed but

insert into matrix_params values (2,3);

Should fail.

A simple constraint for matrix_params does not work as it has no way of knowing what the corresponding type is in the plugins table.


回答1:


You can use a CHECK constraint for this. You can't put a query in a CHECK constraint but you can call a function; so, we build a simple function that tells us if a pluginid is a matrix:

create or replace function is_matrix(int) returns boolean as $$
    select exists (
        select 1
        from plugins
        where id   = $1
          and type = 'matrix'
    );
$$ language sql;

and wrap that in a CHECK constraint:

alter table matrix_params add constraint chk_is_matrix check (is_matrix(pluginid));

Then:

=> insert into matrix_params values (1,1);
=> insert into matrix_params values (2,3);
ERROR:  new row for relation "matrix_params" violates check constraint "chk_is_matrix"

And the FK takes care of referential integrity and cascades.




回答2:


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)
);



回答3:


One way of handling this is to use serializable transactions.

http://wiki.postgresql.org/wiki/SSI#FK-Like_Constraints



来源:https://stackoverflow.com/questions/10135754/how-to-make-a-foreign-key-with-a-constraint-on-the-referenced-table-in-postgresq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!