在 MySQL 中允许空值的唯一约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1346765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:00:00  来源:igfitidea点击:

Unique constraint that allows empty values in MySQL

mysqldatabase-designconstraints

提问by The Disintegrator

I have a field that stores product codes. The codes are unique, but some products simply doesn't have a code. I can't invent codes because those are providers codes.

我有一个存储产品代码的字段。代码是唯一的,但有些产品根本没有代码。我不能发明代码,因为那些是提供者代码。

Is this kind of constraint possible in MySQL?

这种约束在 MySQL 中可能吗?

I'm a noob with stored procedures and triggers, so if the solution involves one of these, please be patient.

我是存储过程和触发器的菜鸟,所以如果解决方案涉及其中之一,请耐心等待。

Update: The column is NOT Null. That's why I was unable to do this.

更新:该列不为空。这就是我无法做到这一点的原因。

回答by

Yes, you can do this. See the MySQL reference (version 5.5).

是的,你可以这样做。请参阅MySQL 参考(版本 5.5)

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL.

UNIQUE 索引创建一个约束,使得索引中的所有值都必须是不同的。如果您尝试添加具有与现有行匹配的键值的新行,则会发生错误。对于所有引擎,UNIQUE 索引允许包含 NULL 的列有多个 NULL 值。

回答by chaos

Yes, if you make the product code column nullable (not declared with NOT NULL), the unique key will allow multiple rows with NULLproduct codes.

是的,如果您使产品代码列可以为空(未用 声明NOT NULL),则唯一键将允许具有NULL产品代码的多行。

回答by cg.

MySQL still allows for multiple rows to have a value of NULLin a unique column.

MySQL 仍然允许多行在NULL唯一列中具有值。