MySQL 时间类型 datetime、bigint、timestamp,选哪个?
数据库中可以用datetime、bigint、timestamp来表示时间,那么选择什么类型来存储时间比较合适呢?
前期数据准备
数据表:
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
实体类users
/**
* @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;
}
dao层接口
/**
* @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());
}
}
}
sql查询速率测试
通过datetime类型查询:
select count(*) from users where time_date >="2018-10-21 23:32:44" and time_date <="2018-10-21 23:41:22"
通过timestamp类型查询
select count(*) from users where time_timestamp >= "2018-10-21 23:32:44" and time_timestamp <="2018-10-21 23:41:22"
通过bigint类型查询
select count(*) from users where time_long >=1540135964091 and time_long <=1540136482372
结论 在InnoDB存储引擎下,通过时间范围查找,性能bigint > datetime > timestamp
sql分组速率测试
通过datetime类型分组:
select time_date, count(*) from users group by time_date
通过timestamp类型分组:
select time_timestamp, count(*) from users group by time_timestamp
结论 在InnoDB存储引擎下,通过时间分组,性能timestamp > datetime,但是相差不大
sql排序速率测试
通过datetime类型排序:
select * from users order by time_date
通过timestamp类型排序
select * from users order by time_timestamp
通过bigint类型排序
select * from users order by time_long
结论 在InnoDB存储引擎下,通过时间排序,性能bigint > timestamp > datetime
小结
推荐阅读:
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
朕已阅