在MySQL中允许空值的唯一约束 [英] Unique constraint that allows empty values in MySQL

查看:247
本文介绍了在MySQL中允许空值的唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



MySQL中是否有这种限制?



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



更新:
列不是空值。这就是为什么我无法做到这一点。

解决方案

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


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



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?

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.

解决方案

Yes, you can do this. See the MySQL reference (version 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.

这篇关于在MySQL中允许空值的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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