目录媒介近来在做数据迁移的时间,利用的是云平台自带的同步工具,在预检查阶段,其时报错 explicit_defaults_for_timestamp 参数在目的端为 off 发起修改 on,有什么风险呢?在此记录下。 测试对比MySQL 默认环境下 explicit_defaults_for_timestamp = 0 我们对比一下看看。 explicit_defaults_for_timestamp = 0在 explicit_defaults_for_timestamp 参数即是 0 的状态下,如果第一个 timestamp 类型的字段如果没有设置 null 将会自动加上 not null 和默认值。如果设置了默认值,则会自动加上 not null,其他类型的字段是不会的。 [code]create table test03 ( a_time timestamp , b_time timestamp null , c_time timestamp default '2024-01-01 00:00:00', name varchar(2) default 'a'); [/code] [code]show create table test03;[/code] [code]CREATE TABLE `test03` ( `a_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `b_time` timestamp NULL DEFAULT NULL, `c_time` timestamp NOT NULL DEFAULT '2024-01-01 00:00:00', `name` varchar(2) DEFAULT 'a' ) ENGINE=InnoDB DEFAULT CHARSET=latin1 [/code]然后,我们尝试插入一个记录: [code]insert into test03 values (null, null, null, null); [/code]
可以看到,在 explicit_defaults_for_timestamp 即是 0 的时间,不但会影响表结构,还会影响写入。虽然 timestamp 是 not null 我们写入 null 后变为了 CURRENT_TIMESTAMP。 如果此时将参数设置为 1,实行相同的 SQL 语句则会报错: [code]# 设置参数为 1 set global explicit_defaults_for_timestamp = 1; # 插入相同的数据 insert into test03 values (null, null, null, null); [/code] [code][23000][1048] Column ‘a_time’ cannot be null[/code]explicit_defaults_for_timestamp = 1此时在 explicit_defaults_for_timestamp 即是 1 的条件下,实行一个刚才的建表语句: [code]create table test04 ( a_time timestamp , b_time timestamp null , c_time timestamp default '2024-01-01 00:00:00', d_time timestamp not null ); [/code] [code]show create table test04;[/code] [code]CREATE TABLE `test04` ( `a_time` timestamp NULL DEFAULT NULL, `b_time` timestamp NULL DEFAULT NULL, `c_time` timestamp NULL DEFAULT '2024-01-01 00:00:00', `d_time` timestamp NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 [/code]尝试插入数据: [code]insert into test04 values (null, null, null, null); [/code]
从上面可以看到,参数开启的环境下,MySQL 默认会为 timestamp 为 NULL 的字段添加 default null 属性。而且 MySQL 没有为第一个 timestamp 设置默认值,当我写入 null 后,则按照 null 来存储。 别的,如果 timestamp 设置为 not null 那么写入 null 时会报错,如果 sql_mode 中不包罗 SQL_MODE 的话,则存储为 ‘0000-00-00 00:00:00’ 并抛出一个非常。 总结生产环境 timestamp 字段一般都会设置为如下样式,而且需要 timestamp 字段为 null 的业务场景很少。 [code]`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', [/code]如果生产环境,要修改这个参数,从 0 调整到 1 需要关注的就是 insert 语句,有没有直接图省事插入 null 表示当前时间,如果有这种不规范的语法,那么调整该参数后,可能会报错。 云平台一般不会给用户 super 账号,所以在迁移过程中,可能无法设置 session 级别的参数,此时发起跳过该校验,不修改全局级别的参数。 到此这篇关于MySQL 迁移中 explicit_defaults_for_timestamp参数影响的文章就介绍到这了,更多相干MySQL explicit_defaults_for_timestamp参数内容请搜索脚本之家以前的文章或继承浏览下面的相干文章盼望各人以后多多支持脚本之家! 来源:https://www.jb51.net/database/3271177o8.htm 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|手机版|小黑屋|梦想之都-俊月星空
( 粤ICP备18056059号 )|网站地图
GMT+8, 2025-7-1 20:13 , Processed in 0.039265 second(s), 18 queries .
Powered by Mxzdjyxk! X3.5
© 2001-2025 Discuz! Team.