“
數據庫中可以用datetime、bigint、timestamp來表示時間,那么選擇什么類型來存儲時間比較合適呢?
前期數據準備
通過程序往數據庫插入50w數據
CREATE?TABLE?`users`?(`id`?int(11)?NOT?NULL?AUTO_INCREMENT,`time_date`?datetime?NOT?NULL,`time_timestamp`?timestamp?NOT?NULL?DEFAULT?CURRENT_TIMESTAMP?ON?UPDATE?CURRENT_TIMESTAMP,`time_long`?bigint(20)?NOT?NULL,PRIMARY?KEY?(`id`),KEY?`time_long`?(`time_long`),KEY?`time_timestamp`?(`time_timestamp`),KEY?`time_date`?(`time_date`)
)?ENGINE=InnoDB?AUTO_INCREMENT=500003?DEFAULT?CHARSET=latin1
其中time_long、time_timestamp、time_date為同一時間的不同存儲格式
/***?@author?hetiantian*?@date?2018/10/21*?*/
@Builder
@Data
public?class?Users?{/***?自增唯一id*?*/private?Long?id;/***?date類型的時間*?*/private?Date?timeDate;/***?timestamp類型的時間*?*/private?Timestamp?timeTimestamp;/***?long類型的時間*?*/private?long?timeLong;
}
/***?@author?hetiantian*?@date?2018/10/21*?*/
@Mapper
public?interface?UsersMapper?{@Insert("insert?into?users(time_date,?time_timestamp,?time_long)?value(#{timeDate},?#{timeTimestamp},?#{timeLong})")@Options(useGeneratedKeys?=?true,keyProperty?=?"id",keyColumn?=?"id")int?saveUsers(Users?users);
}
public?class?UsersMapperTest?extends?BaseTest?{@Resourceprivate?UsersMapper?usersMapper;@Testpublic?void?test()?{for?(int?i?=?0;?i?<?500000;?i++)?{long?time?=?System.currentTimeMillis();usersMapper.saveUsers(Users.builder().timeDate(new?Date(time)).timeLong(time).timeTimestamp(new?Timestamp(time)).build());}}
}
生成數據代碼方至github:https://github.com/TiantianUpup/sql-test/ 如果不想用代碼生成,而是想通過sql文件倒入數據,附sql文件網盤地址:https://pan.baidu.com/s/1Qp9x6z8CN6puGfg-eNghig
sql查詢速率測試
select?count(*)?from?users?where?time_date?>="2018-10-21?23:32:44"?and?time_date?<="2018-10-21?23:41:22"
耗時:0.171
select?count(*)?from?users?where?time_timestamp?>=?"2018-10-21?23:32:44"?and?time_timestamp?<="2018-10-21?23:41:22"
耗時:0.351
select?count(*)?from?users?where?time_long?>=1540135964091?and?time_long?<=1540136482372
耗時:0.130s
sql分組速率測試
使用bigint 進行分組會每條數據進行一個分組,如果將bigint做一個轉化在去分組就沒有比較的意義了,轉化也是需要時間的
select?time_date,?count(*)?from?users?group?by?time_date
耗時:0.176s
select?time_timestamp,?count(*)?from?users?group?by?time_timestamp
耗時:0.173s
sql排序速率測試
select?*?from?users?order?by?time_date
耗時:1.038s
select?*?from?users?order?by?time_timestamp
耗時:0.933s
select?*?from?users?order?by?time_long
耗時:0.775s
小結
如果需要對時間字段進行操作(如通過時間范圍查找或者排序等),推薦使用bigint,如果時間字段不需要進行任何操作,推薦使用timestamp,使用4個字節保存比較節省空間,但是只能記錄到2038年記錄的時間有限
總結
以上是生活随笔為你收集整理的我脸都问绿了!二面竟然被问到 MySQL 时间类型 datetime、bigint 及 timestamp 的查询效率。。。的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。