我很好奇为什么一些非空列已经设置了默认值,但是在插入sql脚本期间,它会抛出错误。
这是样本表
drop table if exists `delivery`;
create table `delivery`(
`price` BIGINT not null default 0,
`created_time` TIMESTAMP(6) not null default CURRENT_TIMESTAMP (6)
) ENGINE=INNODB DEFAULT CHARSET=UTF8MB4
;假设执行下面的三条语句,只有第二条语句不会抛出错误
insert into `delivery` (`price`,`created_time`) values (null, null);
insert into `delivery` (`price`,`created_time`) values (1, null);
insert into `delivery` (`price`,`created_time`) values (null, now());那么,它是否必须为bigint数据类型列插入null并使其执行成功?任何关于背后逻辑的想法。
发布于 2020-04-16 17:45:44
不能插入空值,因为列上有NOT NULL约束。
第一条和第三条语句抛出一个错误,因为您试图在列price和/或created_time中插入一个空值,这显然不满足约束。
如果确实希望允许空值,则删除列上的NOT NULL约束。
或者,您可以通过成功地运行语句,如下所示:
insert into `delivery` () values ();
insert into `delivery` (`price`) values (1);
insert into `delivery` (`created_time`) values (now());
select * from `delivery`;结果:
price created_time
----- --------------------------
0 2020-04-16 09:48:23.505147
1 2020-04-16 09:48:25.549202
0 2020-04-16 09:48:26.0 编辑
第二个查询实际上在MySQL 5.7中成功;它默认忽略显式空值并使用默认值。
该行为似乎是在MySQL 8.x中修复的,因为它现在失败了(正如它应该做的那样)。
https://stackoverflow.com/questions/61256420
复制相似问题