Unique constraint that check two columns in MySQL

后端 未结 1 1538
情书的邮戳
情书的邮戳 2021-01-21 13:41

I would like to add a unicity constraint on my MySQL table. This table contains four columns :

ID | NAME | ADDRESS1 | ADDRESS2

This constraint

相关标签:
1条回答
  • 2021-01-21 14:27

    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.

    0 讨论(0)
提交回复
热议问题