gpt4 book ai didi

MYSQL insert null for not null default column

转载 作者:行者123 更新时间:2023-12-05 05:04:04 24 4
gpt4 key购买 nike

我很好奇为什么有些非空列已经设置了默认值,但是在插入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 并使其执行成功?以及背后逻辑的任何想法。

最佳答案

您不能插入空值,因为您在列上有 NOT NULL 约束。

第一条和第三条语句抛出错误,因为您试图将空值插入列 price 和/或 created_time,这显然不满足约束条件。

如果您真的想允许空值,请删除列上的 NOT NULL 约束。

或者,您可以成功运行您的 SQL 语句,如下所示:

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 中修复,因为它现在失败了(应该如此)。

关于MYSQL insert null for not null default column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61256420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com