我们一般使用字段类型int(11)时间戳来保存时间,这样方便查询时提高效率。但这样有个缺点,显示的时间戳,很难知道真实日期时间。
mysql提供了一个时间戳格式化函数from_unixtime来转换格式
from_unxitime语法说明:
from_unixtime(unix_timestamp, format)
返回Unix时间标记的一个字符串,根据format格式化。如果format为空默认会使用%Y-%m-%d %H:%i:%s的格式
例如:
mysql> select from_unixtime(1459338786); +---------------------------+ | from_unixtime(1459338786) | +---------------------------+ | 2016-03-30 19:53:06 | +---------------------------+ 1 row in set (0.00 sec) mysql> select from_unixtime(1459338786, '%Y-%m-%d %H:%i:%s'); +------------------------------------------------+ | from_unixtime(1459338786, '%Y-%m-%d %H:%i:%s') | +------------------------------------------------+ | 2016-03-30 19:53:06 | +------------------------------------------------+ 1 row in set (0.00 sec)
format格式说明:
实例:按小时统计数量
mysql> select from_unixtime(addtime,'%Y-%m-%d %H') as date,count(*) from `table` group by from_unixtime(addtime,'%Y-%m-%d %H');+---------------+----------+| date | count(*) |+---------------+----------+| 2016-03-30 19 | 409 || 2016-03-30 20 | 161 |+---------------+----------+2 rows in set (0.00 sec)
总结