1. 程式人生 > >mysql timestamp和long儲存時間效率比較

mysql timestamp和long儲存時間效率比較

show create table 20130107date;

CREATE TABLE `20130107date` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `c_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `c_date_long` int(20) NOT NULL,
  `idx_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `idx_date_long` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `20130107date_idx_date`
(`idx_date`), KEY `20130107date_idx_long` (`idx_date_long`) ) ENGINE=InnoDB

裡面有90w資料,都是隨機的時間.
先看沒有索引的全表掃描

1 :

select COUNT(*) from 20130107date
where c_date BETWEEN DATE('20110101') and DATE('20110102')

這個需要1.54s

2:

select COUNT(*) from 20130107date
where c_date_long BETWEEN UNIX_TIMESTAMP('20110101'
) and UNIX_TIMESTAMP('20110102')

這個是2.3s

但是可以這樣搞
3 :

select UNIX_TIMESTAMP('20110101'),UNIX_TIMESTAMP('20110102');

得到結果1293811200和1293897600

然後

select COUNT(*) from 20130107date
where c_date_long BETWEEN 1293811200 and 1293897600

發現變成了0.61s
1和2的差距還可以說是比較int和比較timestamp的差距,那麼2和3的差距呢?難道多出來的時間是每一條記錄都要evaluate UNIX_TIMESTAMP(‘20110102’)?

然後用索引

select COUNT(*) from 20130107date
where idx_date_long BETWEEN UNIX_TIMESTAMP('20110101') and UNIX_TIMESTAMP('20110102');

select COUNT(*) from 20130107date
where idx_date BETWEEN '20110101' and '20110102'

毫無懸念,兩個基本都是瞬時的.