简体   繁体   English

检查 MySQL 中两列的唯一约束

[英]Unique constraint that check two columns in MySQL

I would like to add a unicity constraint on my MySQL table.我想在我的 MySQL 表上添加一个唯一性约束。 This table contains four columns :该表包含四列:

ID | NAME | ADDRESS1 | ADDRESS2

This constraint must check that for a new row, the new address1 and address2 are not contained either in ADDRESS1 nor ADDRESS2 .此约束必须检查新行的新address1address2不包含在ADDRESS1ADDRESS2

Example :例子 :

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

Is there a way to define a such constraint ?有没有办法定义这样的约束?

You can do it with a BEFORE trigger this way您可以通过这种方式使用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);

Note: Since you're using a MySQL version that lacks SIGNAL the trick is to violate NOT NULL constraint on one of the columns when rows with the same address have been found.注意:由于您使用的是缺少SIGNAL的 MySQL 版本,因此当找到具有相同地址的行时,将违反其中一列的NOT NULL约束。

Here is SQLFiddle demo.这是SQLFiddle演示。 Uncomment one of the last insert statements and click Build Schema .取消对最后一个插入语句之一的注释,然后单击Build Schema These inserts won't succeed.这些插入不会成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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