前言
在 Web 应用方面 MySQL 是最常见,最好的关系型数据库之一。非常多网站都选择 MySQL 作为网站数据库。
业务
在数据库的使用中,经常需要按指定日期来查询记录,以便于统计,而在数据库中,有很多存储的是时间戳,也有的直接存日期,查询的时候可能不是那么好弄.
mysql提供了两个函数:
from_unixtime(time_stamp) -> 将时间戳转换为日期
unix_timestamp(date) -> 将指定的日期或者日期字符串转换为时间戳
列如:
- from_unixtime(time_stamp)
select from_unixtime(1382544000);
- unix_timestamp(date)
select unix_timestamp(date('2013-10-24'));
如果要查询当天的订单的记录:
select count(*) from b_order Where date_format(from_unixtime(create_time),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')
# 或者这样
select count(*) from b_order Where create_time >= unix_timestamp('2013-10-24 00:00:00') and create_time <= unix_timestamp('2013-10-24 23:59:59') ;
另外一种就是后台直接出入时间戳 System.currentTimeMillis()
create_time/1000 是因为我存的时间戳是精确到毫秒的,如果你存的时间戳精确到秒,则不需要除以1000
例如一个需要统计每天插入了多少数据的需求
select FROM_UNIXTIME(create_time/1000,'%Y-%m-%d')as date,COUNT(*)
FROM table_1
where 1
GROUP BY date;