MySQL主键字段添加NOT NULL有什么意义?
将 NOT NULL
添加到主键字段有什么意义?主键已经不为空 + 唯一。
这是一个例子:
CREATE TABLE student (
id int(11) AUTO_INCREMENT NOT NULL,
name varchar(255),
PRIMARY KEY(id)
)
为什么不这样定义它:
CREATE TABLE student (
id int(11) AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY(id)
)
What's the point of adding NOT NULL
to a primary key field? Primary key is already not null + unique.
Here is an example:
CREATE TABLE student (
id int(11) AUTO_INCREMENT NOT NULL,
name varchar(255),
PRIMARY KEY(id)
)
Why not to define it like this instead:
CREATE TABLE student (
id int(11) AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY(id)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
他们是一样的。主键
NOT NULL
自动。They are the same. Primary key got
NOT NULL
automatically.你问,为什么人们在不必要的时候还要添加 NOT NULL 呢?我想只是因为它是好的风格。并向读者明确说明。
You are asking, why do people bother adding the NOT NULL when it is unnecessary? Just because it is good style, I guess. And makes it explicit to the reader.
NULL
不等于NULL
(因为NULL
表示未知或不存在的值),因此您将被允许拥有多个具有 < code>NULL 作为 id,即使定义了主键/唯一约束,因此使用NOT NULL
。如果 MySql 甚至允许您在可为空的字段上定义主键的话。此外,由于主键经常在其他表的外键中使用,因此拥有一个或多个 NULL 值是没有意义的。
NULL
is not equivalent toNULL
(asNULL
indicates an unknown or absent value), so you will be permitted to have multiple records that haveNULL
for the id, even though there's a primary key / unique constraint defined, hence the use ofNOT NULL
. That's if MySql even allows you to define a primary key on a nullable field.In addition, as a primary key is often used in a foreign key in other tables, having one or more
NULL
values wouldn't make sense.如果在声明
PRIMARY KEY
时未声明NOT NULL
,则NOT NULL
会隐式添加到PRIMARY KEY
中,因此PRIMARY KEY
带或不带NOT NULL
是一样的。MySQL 文档如下图所示:
另外,MySQL 文档 如下图所示:
If
PRIMARY KEY
is declared withoutNOT NULL
,NOT NULL
is added toPRIMARY KEY
implicitly soPRIMARY KEY
with or withoutNOT NULL
is the same.The MySQL documentation says as shown below:
And also, the MySQL documentation says as shown below: