检查MySQL中两列的唯一约束

时间:2014-01-03 10:31:04

标签: mysql sql unique-constraint

我想在我的MySQL表上添加一个unicity约束。该表包含四列:

ID | NAME | ADDRESS1 | ADDRESS2

此约束必须检查新行address1address2中是否包含新ADDRESS1ADDRESS2

示例:

INSERT INTO MYTABLE (ADDRESS1, ADDRESS2) values ('A', 'B'); -- OK
INSERT INTO MYTABLE (ADDRESS1, ADDRESS2) values ('C', 'D'); -- OK
INSERT INTO MYTABLE (ADDRESS1, ADDRESS2) values ('E', 'A'); -- Fails because A exists in ADDRESS1
INSERT INTO MYTABLE (ADDRESS1, ADDRESS2) values ('D', 'F'); -- Fails because D exists in ADDRESS2

有没有办法定义这样的约束?

1 个答案:

答案 0 :(得分:0)

你可以用BEFORE触发器这样做

CREATE TRIGGER tg_bi_mytable
BEFORE INSERT ON mytable
FOR EACH ROW
  SET NEW.address1 = IF(EXISTS
     (
       SELECT * 
        FROM mytable 
       WHERE address1 IN(NEW.address1, NEW.address2) 
          OR address2 IN(NEW.address1, NEW.address2)
     ), NULL, NEW.address1);

注意:由于您使用的是缺少SIGNAL的MySQL版本,当具有相同地址的行具有相同地址时,其中一个列会违反NOT NULL约束被发现了。

这是 SQLFiddle 演示。取消注释最后一个插入语句,然后单击Build Schema。这些插入不会成功。