mysql 小例子

mysql 小例子

show databases ;
create database company;
use company;

DROP TABLE IF EXISTS employee;

create table employee ( id INT AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY(id)) ENGINE=InnoDB;
DESCRIBE employee ;

111

CREATE TABLE example (
    id INT PRIMARY KEY AUTO_INCREMENT,
    data VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

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 !

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值