mysql的timestamp注意事项

一、时间取值范围

datetime类型取值范围:1000-01-01 00:00:00 到 9999-12-31 23:59:59

timestamp类型取值范围:1970-01-01 00:00:00 到 2037-12-31 23:59:59

timestamp类型具有自动初始化和自动更新的特性。

二、timestamp自动更新的机制

2.1 下面列举下那些情况会自动更新

第一个timestamp的字段,不指定是否为空默认为not null,

下方test1和test2中create_date 都会自动更新

create table test1 (
 id int primary key ,
 create_date timestamp ,
 update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

create table test2 (
 id int primary key ,
 create_date timestamp not null ,
 update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

还有一种情况会自动更新:

指定更新是自动更新eg: ON UPDATE CURRENT_TIMESTAMP

下面举一个例子:允许为空的时候,指定更新时自动更新

create table test5 (
 id int primary key ,
 create_date timestamp null on update current_timestamp,
 update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

test5:插入的时候,不会插入时间

更新的时候,会自动更新create_date

2.2 下面列举下哪些情况不会自动更新

第一个timestamp,指定允许为null,或者指定默认值,not null default CURRENT_TIMESTAMP

create table test3 (
  id int primary key ,
  create_date timestamp null,
  update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
 
create table test4 (
 id int primary key ,
 create_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

允许为null,则插入和更新都不会自动插入该值

不允许为null,有默认值,第一次插入的时候会自动插入 默认值,更新的时候不会在自动更新该字段的值

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值