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

前端 未结 6 810
遥遥无期
遥遥无期 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:41

    I think this is not the best way to model the situation of a single default value.

    Instead, I would leave the IsDefault column out and create a separate table with one row and only the column(s) that make(s) up the primary key of your main table. In this table you place the PK value(s) that identify the default record.

    This results in considerably less storage and avoids the update issue of temporarily not having a default value (or, alternatively, temporarily having two default values) when you update.

    You have numerous options for ensuring that there is one-and-only-one row in the default table.

提交回复
热议问题