简体   繁体   中英

SQL complex unique constraint

I have a table mytable where is the 2 unique int field

# SQLAlchemy example
mytable = Table('mytable', meta,

# per-column anonymous unique constraint
Column('col1', Integer, unique=True),
Column('col2', Integer, unique=True),

# explicit/composite unique constraint.  'name' is optional.
UniqueConstraint('col1', 'col2', name='uix_1')
)

How to do restrictions like this:

col1 col2
1      
2     6
3     1
4     5
5
6     1 -- FAIL: becouse 3-1 is exist and 2-6 is exist!!!

unique((col1, col2) union (col2, col1))

You can use something like this as a constraint:

create table example (
    col1 integer,
    col2 integer,
    CHECK (col1 < col2),
    UNIQUE(col1, col2)
);

If you want it to automatically make the col1 smaller than col2, use a trigger :)

I think you can't achieve this using a constraint.

You could use a trigger:

CREATE TABLE test (a int, b int);

CREATE OR REPLACE FUNCTION fun_test()
  RETURNS trigger
  LANGUAGE plpgsql
AS
$body$
BEGIN
    if (TG_OP = 'INSERT') then
        if (exists(SELECT 1 FROM test t WHERE t.b = NEW.a) -- or whatever condition you want
            and exists(SELECT 1 FROM test t WHERE t.b = NEW.b))
          then
            RAISE EXCEPTION 'Can''t insert (%,%)', NEW.a, NEW.b;
        end if;
    return NEW;
    end if;
END;    
$body$

  CREATE TRIGGER tgr_test BEFORE INSERT
      ON test FOR EACH ROW
 EXECUTE PROCEDURE fun_test();

Note you should also check the updates.

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