Question

I would like to add a unicity constraint on my MySQL table. 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.

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 ?

Was it helpful?

Solution

You can do it with a BEFORE trigger this way

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.

Here is SQLFiddle demo. Uncomment one of the last insert statements and click Build Schema. These inserts won't succeed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top