在mysql 5.6中,对字段设定not null且指定默认值,实际插入的值会与插入的方式的不同有些关系,下面是实验的结果。
先看下表结构
单条插入null值
不指定任何值
批量插入null
批量插入的情况就有点妖了,不但插入成功,插入的值还是个莫名其妙的0,既不是指定的null,也不是默认值-1。
关于插入0的解释如下:
https://dev.mysql.com/doc/refman/5.6/en/insert.html
Inserting NULL
into a column that has been declared NOT NULL
. For multiple-row INSERT
statements or INSERT INTO ... SELECT
statements, the column is set to the implicit default value for the column data type. This is 0
for numeric types, the empty string (''
) for string types, and the “zero” value for date and time types. INSERT INTO ... SELECT
statements are handled the same way as multiple-row inserts because the server does not examine the result set from the SELECT
to see whether it returns a single row. (For a single-row INSERT
, no warning occurs when NULL
is inserted into a NOT NULL
column. Instead, the statement fails with an error.)
上面的解释说明了两点。
- 往设置not null的列里插入null值,批量插入时可以成功的。
- 插入的实际值为一个隐式的默认值,而不是该字段指定的默认值。这个隐式默认值取决于字段类型,对于数字就是0,对于string就是’’,对于时间就是zero。
改变一下sql_mode
可见,在严格模式下,多条插入情况往not null字段插入null值也失败了。
mysql5.7 默认的sql_mode就是严格模式,测试下在mysql5.7的适用情况。