简体   繁体   中英

Unique constraint across multiple postgres tables

Let's say I have the following two postgres tables with the same field:

CREATE TABLE table1 (
    label VARCHAR(50)
);

CREATE TABLE table2 (
    label VARCHAR(50)
);

I want label to be unique across both tables. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM