I would like to add a unicity constraint on my MySQL table. This table contains four columns :
ID | NAME | ADDRESS1 | ADDRESS2
This constraint
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.