微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数据库 – 主键中允许的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中存在无数的不一致之处,但是这个特殊的一个从来没有超过委员会.

原文地址:https://www.jb51.cc/mssql/82884.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐