How to create a “unique” constraint on a boolean MySQL column?

前端 未结 6 805
遥遥无期
遥遥无期 2020-12-09 08:40

I would like to add a BOOLEAN column to a MySQL table which will be named is_default. In this column, only one record can have is_default

6条回答
  •  情书的邮戳
    2020-12-09 09:34

    You can't have such a constraint in MySQL.

    However if instead of TRUE and FALSE you use the values TRUE and NULL then it will work because a UNIQUE column can have multiple NULL values. Note that this doesn't apply to all databases, but it will work in MySQL.

    CREATE TABLE table1(b BOOLEAN UNIQUE);
    
    INSERT INTO table1 (b) VALUES (TRUE);   // Succeeds
    INSERT INTO table1 (b) VALUES (TRUE);   // Fails: duplicate entry '1' for key 'b'
    
    INSERT INTO table1 (b) VALUES (FALSE);  // Succeeds
    INSERT INTO table1 (b) VALUES (FALSE);  // Fails: duplicate entry '0' for key 'b'
    
    INSERT INTO table1 (b) VALUES (NULL);   // Succeeds
    INSERT INTO table1 (b) VALUES (NULL);   // Succeeds!
    

提交回复
热议问题