标题:问题:数据库中可以用 datetime、bigint、timestamp 来表示时间,那么选择什么类型来存储时间比较合适呢?
前期数据准备:
通往程序往数据库插50w数据
数据表:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200930223131237.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjU4NDc4Mw==,size_16,color_FFFFFF,t_70)
实体类:users
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200930223222243.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjU4NDc4Mw==,size_16,color_FFFFFF,t_70)
sql 查询速率测试
通过 datetime 类型查询:
select count(*) from users where time_date >=“2018-10-21 23:32:44” and time_date <=“2018-10-21 23:41:22”
耗时:0.171
通过 timestamp 类型查询
select count(*) from users where time_timestamp >= “2018-10-21 23:32:44” and time_timestamp <=“2018-10-21 23:41:22”
耗时:0.351
通过 bigint 类型查询
select count(*) from users where time_long >=1540135964091 and time_long <=1540136482372
耗时:0.130s
结论 在 InnoDB 存储引擎下,通过时间范围查找,性能 bigint > datetime > timestamp
sql 分组速率测试:
使用 bigint 进行分组会每条数据进行一个分组,如果将 bigint 做一个转化在去分组就没有比较的意义了,转化也是需要时间的
通过 datetime 类型分组:
select time_date, count(*) from users group by time_date
耗时:0.176s
通过 timestamp 类型分组:
select time_timestamp, count(*) from users group by time_timestamp
耗时:0.173s
结论 在 InnoDB 存储引擎下,通过时间分组,性能 timestamp > datetime,但是相差不大
sql 排序速率测试
通过 datetime 类型排序:
select * from users order by time_date
耗时:1.038s
通过 timestamp 类型排序
select * from users order by time_timestamp
耗时:0.933s
通过 bigint 类型排序
select * from users order by time_long
耗时:0.775s
结论 在 InnoDB 存储引擎下,通过时间排序,性能 bigint > timestamp > datetime
小结:
如果需要对时间字段进行操作 (如通过时间范围查找或者排序等),推荐使用 bigint,如果时间字段不需要进行任何操作,推荐使用 timestamp,使用 4 个字节保存比较节省空间,但是只能记录到 2038 年记录的时间有限。