MySQL中create_time 和 update_time实现自动更新时间
也是最近在捣鼓前后端分离项目, 在写后端接口的时候便设计到数据库表建设, 这里规范显得很重要.
通常的建表规范, 必备三字段:id
,create_time
,update_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 !
耐心和恒心, 总会获得回报的.
分类:
Mysql
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2020-01-17 逻辑思维的规律