为什么主键不能包含空值? [英] Why primary key cannot contain null values?

查看:836
本文介绍了为什么主键不能包含空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到mysql在主键上设置了一个不为null的约束,但是唯一键为列允许一个null值.那么为什么不主键还允许一个空值呢?

I have read that mysql puts a constraint of not null on primary key , but unique key allows one null value for a column. So why not primary key also allows a null value??

推荐答案

PRIMARY KEY列等效于UNIQUE和NOT NULL,并且默认情况下为索引列.
它应该是UNIQUE,因为主键标识表中的行,因此2个不同的行不应具有相同的键.
另外,主键可以在其他表中用作FOREIGN KEY,这就是为什么它不能为NULL的原因,以便其他表可以在引用表中查找行.

A PRIMARY KEY column is equivalent to UNIQUE and NOT NULL and is indexed column by default.
It should be UNIQUE because a primary key identifies rows in a table so 2 different row should not have the same key.
In addition a primary key may be used a FOREIGN KEY in other tables and that's why it cannot be NULL so that the other table can fin the rows in the referenced table.

例如:

CREATE person{   
   id INT PRIMARY KEY,  -- equals UNIQUE NOT NULL   
   name VARCHAR(20)   
};   

CREATE family{   
   id INT PRIMARY KEY,  -- equals UNIQUE NOT NULL   
   menber_id INT FOREIGN KEY REFERENCE person(id)   
};   

这篇关于为什么主键不能包含空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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