timestamp翻译为汉语即”时间戳”,它是当前时间到 unix元年(1970 年 1 月 1 日 0 时 0 分 0 秒)的秒数,占用4个字节,而且是以utc的格式储存,它会自动检索当前时区并进行转换。datetime以8个字节储存,不会进行时区的检索。也就是说,对于timestamp来说,如果储存时的时区和检索时的时区不一样,那么拿出来的数据也不一样。对于datetime来说,存什么拿到的就是什么。下面给出几个常见案例及选择建议。
根据存储范围来选取,比如生产时间,保质期等时间建议选取datetime,因为datetime能存储的范围更广。
记录本行数据的插入时间和修改时间建议使用timestamp。
和时区相关的时间字段选用timestamp。
如果只是想表示年、日期、时间的还可以使用 year、 date、 time,它们分别占据 1、3、3 字节,而datetime就是它们的集合。
如果timestamp字段经常用于查询,我们还可以使用mysql内置的函数from_unixtime()、unix_timestamp(),将日期和时间戳数字来回转换,转换后可以用 int unsigned 存储时间,数字是连续的,占用空间更小,并且可以使用索引提升查询性能。下面给出示范建表语句及时间戳相关转换sql:
create table `tb_time` ( `increment_id` int unsigned not null auto_increment comment '自增主键', `col1` datetime not null default '2020-10-01 00:00:00' comment '到期时间', `unix_createtime` int unsigned not null comment '创建时间戳', `create_time` timestamp not null default current_timestamp comment '创建时间', `update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间', primary key (`increment_id`), key `idx_unix_createtime` (`unix_createtime`)) engine=innodb default charset=utf8 comment='time测试表';# 插入数据insert into tb_time (unix_createtime,create_time) values (unix_timestamp(now()),now());# 时间戳数字与时间相互转换select unix_timestamp('2020-05-06 00:00:00')select from_unixtime(1588694400)
以上就是mysql中时间类型有哪些的详细内容。
