首页 > 解决方案 > 使用函数和检查约束或约束触发器的多个表的外键?

问题描述

我有一个简单的问题。请不要问为什么。

我有两个表,data1 和 data2。它们都有主键 id 列。保证每个表中的值在两个表中都是唯一的。这是由检查约束强制执行的。

我有第三个表 (data3),其中有一列应该只包含存在于 data1.id 或 data2.id 中的值。我不能使用常规外键来强制执行此操作。所以我写了一个函数,通过检查约束来做到这一点。

有没有更好的方法使用触发约束来做到这一点?

drop schema if exists test cascade;
create schema test;

CREATE FUNCTION test.right_bit_shift()
    RETURNS bigint IMMUTABLE LANGUAGE SQL AS
'SELECT 2::bigint';

create or replace function test.ufn_get_type_id(id bigint) returns bigint as $$
select id >> 2;
$$ language sql
;

create table test.data1(name text);
alter table test.data1 add column id bigint primary key constraint id_chk check(test.ufn_get_type_id(id) =1) no inherit ;

create table test.data2(name text);
alter table test.data2 add column id bigint primary key constraint id_chk check(test.ufn_get_type_id(id) =0) no inherit ;

insert into test.data1(id, name) values(5,'101');
insert into test.data2(id, name) values(1,'001');

create table test.table_lookup(type_id bigint, table_name text);

insert into test.table_lookup(type_id, table_name)
values
(1, 'test.data1'),
(0, 'test.data2');    


create or replace function test.ufn_get_existence_sql(_id bigint) returns text as $$
    select
            'select exists(select 1 from '||table_name||' where id = '||_id||');'
    from test.table_lookup where type_id = test.ufn_get_type_id(_id);
    $$
language sql;


create or replace function test.ufn_id_exists (id_to_check bigint) returns boolean as $$
    declare res bool;
begin
    execute test.ufn_get_existence_sql(id_to_check) into res;
    return res;
end;
$$
    language plpgsql;

create table test.data3(name text, fk_id bigint constraint fk_id check ( test.ufn_id_exists(fk_id) ));

标签: postgresql

解决方案


所以我发现了这个

https://dba.stackexchange.com/questions/75613/disable-all-constraints-and-table-checks-while-restoring-a-dump/75635#75635

它指出检查约束应该是不可变的,而我的检查约束当然不是。它可能会导致恢复转储等问题。

所以似乎最好的方法是插入和更新触发器。


推荐阅读