数据库 – 主键中允许的NULL – 为什么和哪个DBMS?

前端之家收集整理的这篇文章主要介绍了数据库 – 主键中允许的NULL – 为什么和哪个DBMS?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
继续我的问题 “Why to use ´not null primary key´ in TSQL?”

正如我从其他讨论中理解的,一些RDBMS(例如sqlite,MysqL)在主键中允许“唯一”NULL.

为什么这是允许的,它可能如何有用?

背景:我认为有助于与同事和数据库专业人员沟通,了解不同DBMS中基本概念,方法及其实现的差异.

笔记

> MysqL被修复并返回到“NOT NULL PK”列表.
>已经添加sqlite(感谢Paul Hadfield)到“NULL PK”列表:

For the purposes of determining the uniqueness of primary key values,NULL values are considered distinct from all other values,including other NULLs.

If an INSERT or UPDATE statement attempts to modify the table content so that two or more rows feature identical primary key values,it is a constraint violation. According to the sql standard,PRIMARY KEY should always imply NOT NULL. Unfortunately,due to a long-standing coding oversight,this is not the case in sqlite.

Unless the column is an INTEGER PRIMARY KEY sqlite allows NULL values in a PRIMARY KEY column. We could change sqlite to conform to the standard (and we might do so in the future),but by the time the oversight was discovered,sqlite was in such wide use that we feared breaking legacy code if we fixed the problem.

So for now we have chosen to continue allowing NULLs in PRIMARY KEY columns. Developers should be aware,however,that we may change sqlite to conform to the sql standard in future and should design new programs accordingly.

— 07001

解决方法

假设你有一个主键包含一个可空的列Kn.

如果你想要第二行被拒绝,理由是在第二行中,Kn是空的,并且表已经包含了一个带有Kn的行,那么你实际上要求系统会对待比较“row1.Kn = row2 .Kn“作为TRUE(因为您以某种方式希望系统检测到这些行中的键值确实相等).但是,该比较归结为比较“null = null”,并且标准已经明确指定了null不等于任何东西,包括它自身.

为了允许你想要的,这将相当于sql偏离自己关于null处理原则的sql. sql中存在无数的不一致之处,但是这个特殊的一个从来没有超过委员会.

猜你在找的MsSQL相关文章