如何创建“唯一”约束在布尔Mysql列? [英] How to create a "unique" constraint on a boolean Mysql column?

查看:110
本文介绍了如何创建“唯一”约束在布尔Mysql列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向一个名为 is_default 的MySQL表添加 BOOLEAN 列。
在此列中,只有一个记录可以将 is_default 设置为 true

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 set to true.

如何使用mysql将此约束添加到我的列?

How can I add this constraint to my column with mysql?

谢谢!

UPDATE

如果不是我应该添加的约束。我们如何处理DB上的这种类型的问题?

If it is not a constraint that I should add. How are we dealing with this type of problem on DBs?

推荐答案

我认为这不是最好的方式来模拟情况一个单一的默认值。

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

相反,我将IsDefault列留出来,创建一个单独的表,一行,只有列(s)您的主表的主键。在此表中,您放置了用于标识默认记录的PK值。

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.

这篇关于如何创建“唯一”约束在布尔Mysql列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆