我想在我的MySQL表上添加一个唯一性约束。该表包含四列:
ID | NAME | ADDRESS1 | ADDRESS2
此约束必须检查对于new行,newaddress1和address2都未包含在ADDRESS1或中ADDRESS2。
address1
address2
ADDRESS1
ADDRESS2
例子 :
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
有没有办法定义这样的约束?
您可以通过BEFORE触发器来做到这一点
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);
注意: 由于您使用的MySQL版本缺少SIGNAL技巧NOT NULL,因此当找到具有相同地址的行时,违反对其中一列的约束。
SIGNAL
NOT NULL
这是 SQLFiddle 演示。取消注释最后一个插入语句之一,然后单击确定Build Schema。这些插入不会成功。
Build Schema