【mysql】mysql not null和defaul

在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.)

上面的解释说明了两点。

  1. 往设置not null的列里插入null值,批量插入时可以成功的。
  2. 插入的实际值为一个隐式的默认值,而不是该字段指定的默认值。这个隐式默认值取决于字段类型,对于数字就是0,对于string就是’’,对于时间就是zero。   

改变一下sql_mode

可见,在严格模式下,多条插入情况往not null字段插入null值也失败了。

mysql5.7 默认的sql_mode就是严格模式,测试下在mysql5.7的适用情况。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值