«

sql时间戳按月份聚合

emer 发布于 2019-4-9 10:04   3516 次阅读     


create_time为时间格式(字段名create_time 根据自己表字段修改,数据库中存为201610071202)

SELECT DATE_FORMAT(create_time,'%Y%u') weeks,COUNT(id) COUNT FROM role GROUP BY weeks; SELECT DATE_FORMAT(create_time,'%Y%m%d') days,COUNT(id) COUNT FROM role GROUP BY days; SELECT DATE_FORMAT(create_time,'%Y%m') months,COUNT(id) COUNT FROM role GROUP BY months;

create_time为时间戳格式(字段名create_time 根据自己表字段修改,数据库中存为1474959640):


SELECT FROM_UNIXTIME(create_time,'%Y%u') weeks,COUNT(id) COUNT FROM role GROUP BY weeks; SELECT FROM_UNIXTIME(create_time,'%Y%m%d') days,COUNT(id) COUNT FROM role GROUP BY days; SELECT FROM_UNIXTIME(create_time,'%Y%m') months,COUNT(id) COUNT FROM role GROUP BY months;




var sqls={
//查询文章 多表join连接
articleSql:"select a.*,b.*,c.username from emlog_blog as a left JOIN emlog_sort AS b on a.sortid =b.sid LEFT JOIN emlog_user as c ON a.author=c.uid WHERE checked='y' and hide='n' order by date desc limit ?,?;select count(*) as total from emlog_blog;SELECT gid,title,views FROM emlog_blog ORDER BY views desc limit 0,5;",
//查询分类 按分类聚合
tagSql:"SELECT COUNT(*) as count,sid,sortname FROM emlog_sort as a,emlog_blog as b WHERE a.sid=b.sortid GROUP BY sortname order by count desc;"
};
module.exports=sqls;

    

mysql中本身支持一种更好的方法来达到上面的效果,那就是使用SQL_CALC_FOUND_ROWS和FOUND_ROWS()函数。见:http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
应用举例:

mysql> 
SELECT SQL_CALC_FOUND_ROWS * FROM 
tbl_name
1

    -> 
WHERE id > 100 LIMIT 10;
1

mysql> 
SELECT FOUND_ROWS();