[英]Unique constraint across multiple postgres tables
Let's say I have the following two postgres tables with the same field:假设我有以下两个具有相同字段的 postgres 表:
CREATE TABLE table1 (
label VARCHAR(50)
);
CREATE TABLE table2 (
label VARCHAR(50)
);
I want label
to be unique across both tables.我希望label
在两个表中都是唯一的。 That is, the following data should raise an error:也就是说,以下数据应该引发错误:
INSERT INTO table1 (label) VALUES ('hello');
INSERT INTO table2 (label) VALUES ('hello');
Is there any way to enforce this at the database level?有没有办法在数据库级别强制执行此操作?
You cannot create a unique constraint across table, but a trigger on both tables can.您不能跨表创建唯一约束,但可以在两个表上创建触发器。 One way: (see demo )一种方式:(见演示)
create or replace function table1_table2_cross_check()
returns trigger
language plpgsql
as $$
begin
if tg_table_name = 'table1'
then
if exists (select null
from table2
where label = new.label
)
then
raise exception 'Executing: % table1, Label Value: ''%'', already exists in table2',tg_op,new.label;
end if;
else
if exists (select null
from table1
where label = new.label
)
then
raise exception 'Executing: % table2, Label Value: ''%'', already exists in table1',tg_op,new.label;
end if;
end if;
return new;
end;
$$;
create trigger table1_biur
before insert or update
on table1
for each row
execute procedure table1_table2_cross_check();
create trigger table2_biur
before insert or update
on table2
for each row
execute procedure table1_table2_cross_check();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.