SQL复杂的唯一约束

时间:2011-11-15 12:10:35

标签: sql postgresql sqlalchemy unique-constraint

我有一个表mytable,其中是2个唯一的int字段

# 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')
)

如何做这样的限制:

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

2 个答案:

答案 0 :(得分:5)

你可以使用这样的东西作为约束:

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

如果您希望它自动使col1小于col2,请使用触发器:)

答案 1 :(得分:1)

我认为你无法使用约束来实现这一点。

您可以使用触发器:

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

请注意,您还应该检查更新。

相关问题