MySQL 添加一个 NOT NULL 列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22868345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL add a NOT NULL column
提问by Paul Draper
I am adding a column to a table:
我正在向表中添加一列:
ALTER TABLE t ADD c varchar(10) NOT NULL;
The column gets added, and each record has the empty string.
该列被添加,每个记录都有空字符串。
Is this expected to work this way under all conditions (strict mode, etc.) in MySQL 5.5+?
在 MySQL 5.5+ 的所有条件下(严格模式等),这是否可以正常工作?
回答by user2864740
In MySQL, each column type has an "implicit default" value.
在 MySQL 中,每个列类型都有一个“隐式默认”值。
For string types [the implicit] default value is the empty string.
对于字符串类型 [隐式] 默认值为空字符串。
If a NOT NULL column is added to a table, and no explicit DEFAULT is specified, the implicit default value is used to populate the new column data1. Similar rules apply when the DEFAULT value is specified.
如果将 NOT NULL 列添加到表中,并且未指定显式 DEFAULT,则使用隐式默认值填充新列数据1。当指定了 DEFAULT 值时,类似的规则适用。
As such, the original DDL produces the same results as:
因此,原始 DDL 产生与以下相同的结果:
-- After this, data will be the same, but schema has an EXPLICIT DEFAULT
ALTER TABLE t ADD c varchar(10) NOT NULL DEFAULT ''
-- Now we're back to the IMPLICIT DEFAULT (MySQL stores NULL internally)
ALTER TABLE t ALTER c DROP DEFAULT
The "strict" mode settings affects DML statements relying on default values, but do not affect the implicit default usage when the column is added.
“严格”模式设置会影响依赖默认值的 DML 语句,但不会影响添加列时的隐式默认用法。
For data entry into a NOT NULL column that has no explicit DEFAULT clause, if an INSERT or REPLACE statementincludes no value for the column [and if] strict SQL mode is enabled, an error occurs ..
对于没有显式 DEFAULT 子句的 NOT NULL 列的数据输入,如果INSERT 或 REPLACE 语句不包含列的值 [并且如果] 启用了严格的 SQL 模式,则会发生错误..
Here is an sqlfiddle "proof"that strict mode does not apply to the ALTER TABLE .. ADD statement.
这是一个 sqlfiddle“证明”,即严格模式不适用于 ALTER TABLE .. ADD 语句。
1This is a MySQL feature. Other engines, like SQL Server, require an explicit DEFAULT (or NULL column) constraint for such schema changes.
1这是一个 MySQL 功能。其他引擎,如 SQL Server,需要明确的 DEFAULT(或 NULL 列)约束来进行此类架构更改。