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 !

相关推荐

  1. mysql 例子

    2024-06-10 19:12:01       30 阅读
  2. Mysql实用SQL例子

    2024-06-10 19:12:01       42 阅读
  3. Pytest 的例子

    2024-06-10 19:12:01       58 阅读
  4. mysql聚合函数andjson_object 例子

    2024-06-10 19:12:01       52 阅读
  5. 程序常用实用例子

    2024-06-10 19:12:01       57 阅读
  6. Python 的chatGPT API例子

    2024-06-10 19:12:01       45 阅读
  7. pandas行选择10个例子

    2024-06-10 19:12:01       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-10 19:12:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-10 19:12:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-10 19:12:01       87 阅读
  4. Python语言-面向对象

    2024-06-10 19:12:01       96 阅读

热门阅读

  1. 服务部署:Ubuntu安装搭建docker

    2024-06-10 19:12:01       39 阅读
  2. 初识manim

    2024-06-10 19:12:01       35 阅读
  3. 数据结构学习笔记-串

    2024-06-10 19:12:01       34 阅读
  4. AcWing 842. 排列数字——算法基础课题解

    2024-06-10 19:12:01       35 阅读
  5. 【Linux】rsync远程数据同步工具使用

    2024-06-10 19:12:01       29 阅读
  6. 代码随想录算法训练营第29天|回溯

    2024-06-10 19:12:01       37 阅读
  7. 浅谈AI-在公司资金管理中的应用

    2024-06-10 19:12:01       30 阅读
  8. Web中常用的数据格式

    2024-06-10 19:12:01       34 阅读
  9. Netty

    Netty

    2024-06-10 19:12:01      33 阅读
  10. SpEL 表达式是什么?

    2024-06-10 19:12:01       26 阅读
  11. Spring (40)Spring Cloud和Spring Boot

    2024-06-10 19:12:01       33 阅读