MySQL中create_time 和 update_time实现自动更新时间

也是最近在捣鼓前后端分离项目, 在写后端接口的时候便设计到数据库表建设, 这里规范显得很重要.

通常的建表规范, 必备三字段:idcreate_timeupdate_time.

  • id 必为主键,类型为 bigint unsigned、单表时自增、步长为 1

  • create_time 类型为 datetime, 数据新增时自动创建

  • update_time 类型为 datetime, 数据更新时被动式更新

drop table if exists test;
create table test (
  id int unsigned primary key auto_increment comment 'id'
  , name varchar(50) not null comment '名称'
  , create_time datetime not null default current_timestamp comment '创建时间'
  , update_time datetime not null default current_timestamp on update current_timestamp comment '更新时间'
) charset=utf8 comment '测试表';

写入两条数据:

# 插入测试
insert into test(name) values ('张三'), ('李四');

然后查询该表, 这时候可以看到 id, create_time, update_time 都自动有值了

select * from test;


id	name	create_time	update_time
1	张三	2024-01-17 22:49:36.0	2024-01-17 22:49:36.0
2	李四	2024-01-17 22:49:36.0	2024-01-17 22:49:36.0

再来验证 update 修改其中的数据

# 更新第二条数据的值
update test set name = '杰哥' where id = 2;

然后再来查询即可看到自动更新:

select * from test;

id	name	create_time	update_time
1	张三	2024-01-17 22:49:36.0	2024-01-17 22:49:36.0
2	杰哥	2024-01-17 22:49:36.0	2024-01-17 22:55:07.0

nice !

posted @ 2024-01-17 23:06  致于数据科学家的小陈  阅读(91)  评论(0编辑  收藏  举报