问题
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)
)
回答1:
They are the same. Primary key got NOT NULL automatically.
回答2:
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.
回答3:
NULL is not equivalent to NULL(as NULL indicates an unknown or absent value), so you will be permitted to have multiple records that have NULL for the id, even though there's a primary key / unique constraint defined, hence the use of NOT 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.
来源:https://stackoverflow.com/questions/3503089/whats-the-point-of-adding-not-null-to-primary-key-field-in-mysql