您現在的位置是:首頁 > 動作武俠首頁動作武俠
MySQL 時間型別 datetime、bigint、timestamp選哪個?很多人答錯了
- 2021-09-07
禮單是什麼
資料庫中可以用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為同一時間的不同儲存格式
實體類users
/** * @author hetiantian * @date 2018/10/21 * */@Builder@Datapublic class Users { /** * 自增唯一id * */ private Long id; /** * date型別的時間 * */ private Date timeDate; /** * timestamp型別的時間 * */ private Timestamp timeTimestamp; /** * long型別的時間 * */ private long timeLong;}複製程式碼
dao層介面
/** * @author hetiantian * @date 2018/10/21 * */@Mapperpublic 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 { @Resource private UsersMapper usersMapper; @Test public 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:github。com/TiantianUpu… 如果不想用程式碼生成,而是想透過sql檔案倒入資料,附sql檔案網盤地址:pan。baidu。com/s/1Qp9x6z8C…
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年記錄的時間有限
作者:噠波甜 連結:https://juejin。cn/post/6844903701094596615