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

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

    I don't think it is a problem with the database as much as it is a problem with your model. It is hard for me to come up with a good example of how to solve it since you haven't mentioned what type of data you are representing, but a XXXType or XXXConfiguration table would be able to hold a defaultXXXId column.

    Think of it like this: Should the color blue know that it is default or should something else know that the color blue is default when used in a given context?

    Changing the way you model your data is often a much better approach to cross-database compatibility than trying to use specific features of one database flavor to represent data in a way that is not necessarily natural to your problem domain if you think about it.

提交回复
热议问题