数据库中可以用 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 {
@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:
https://github.com/TiantianUpup/sql-test/ 如果不想用代码生成,而是想通过 sql 文件导入数据,附 sql 文件网盘地址:
https://pan.baidu.com/s/1Qp9x6z8CN6puGfg-eNghig
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
使用 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
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 年记录的时间有限