mysql 小例子

发布于:2024-06-12 ⋅ 阅读:(40) ⋅ 点赞:(0)

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 !


网站公告

今日签到

点亮在社区的每一天
去签到