• MySQL中datetime与timestamp的区别


    在MySQL常用的场景中,会使用datetime和timestamp两种方式记录数据的时间,一般会精确到秒,主要用于记录每个表中数据的创建时间、修改时间等,甚至在设计表时,根据设计规范,会对每张表都添加一个时间的属性来记录数据的创建时间,也有可能再添加一个属性来记录数据的修改时间。那么下面的介绍会使得设置变得更加方便:

    1.datetime

    1)展现类型(存储内容):YYYY-MM-DD HH:MM:SS,固定占用8字节。

    2)从5.6.5版本开始,可支持毫秒,datetime(n),其中n表示毫秒的长度。

    3)默认值:可设置初始化值为当前时间,以及数据更新时自动更新修改时间。(若不需要默认值则无需设置)

    如用户表需要记录用户信息的创建时间和修改时间,则创建表时对其进行定义:

    create table sys_user (
        id int not null auto_increment,
        user_name varchar(200) not null,
        password varchar(300) not null,
        create_time datetime not null default current_timestamp,
        update_time datetime not null default current_timestamp on update current_timestamp,
    primary key(id) 
    );

    通过设置当前时间(current_timestamp)进行默认值的设置。

    2.timestamp

    1)展现类型(存储内容):从'1970-01-01 00:00:00'开始到现在的毫秒数,固定占用4或7字节。

    2)从5.6.5版本开始,可支持毫秒。不带毫秒是4字节,带毫秒数时就变成了7字节。因此当只有4字节时,其最大只能记录到'2038-01-19 00:00:00'。

    3)默认值:可设置初始化值为当前时间,以及数据更新时自动更新修改时间。

    将上述用户表中datetime类型修改为timestamp类型进行创建:

    create table sys_user1 (
        id int not null auto_increment,
        user_name varchar(200) not null,
        password varchar(300) not null,
        create_time timestamp not null default current_timestamp,
        update_time timestamp not null default current_timestamp on update current_timestamp,
    primary key(id) 
    );

    通过设置当前时间(current_timestamp)进行默认值的设置。

    4)差异:timestamp的优点在于记录的是毫秒数,故具有时区属性。换句话说,就是此毫秒数,在任何时区不同的地方,都可以转化为当地的时间。缺点是存储的时间有局限性。相比之下,推荐使用datetime类型来记录时间。

  • 相关阅读:
    vue 引用本地图片
    antdVue
    Nest.js —— A progressive Node.js framework
    20184313《网络对抗技术》Exp8 Web综合
    20184313《网络对抗技术》Exp7 网络欺诈防范
    20184313《网络对抗技术》Exp6 MSF应用基础
    20184313《网络对抗技术》Exp5 信息搜集与漏洞扫描
    网页激知序列号之途径(网友提供技术参考)
    【转】Delphi中正则表达式支持中文的写法
    遇到的一个奇怪问题
  • 原文地址:https://www.cnblogs.com/zys2019/p/16028465.html
Copyright © 2020-2023  润新知