douluan5738 2018-04-28 13:16
浏览 55
已采纳

Unix时间戳不会工作

Before i used datetime for post created time from database,

SELECT MONTH(created)+1, count(*) 
FROM post_comments
WHERE YEAR(created) = YEAR(CURDATE())
group by MONTH(created)
ORDER BY MONTH(created)

and now i am using unix timestamp. How I need to make a change in the above code, to work it unix timestamp.

Before the created time looks like this: 2018-04-28 09:03:02

and now the created time looks like this: 1524921263

  • 写回答

1条回答 默认 最新

  • duancuo1234 2018-04-28 13:20
    关注

    You can convert everything to dates using FROM_UNIXTIME():

    SELECT MONTH(FROM_UNIXTIME(created))+1, count(*) 
    FROM post_comments
    WHERE YEAR(FROM_UNIXTIME(created)) = YEAR(CURDATE())
    GROUP BY MONTH(FROM_UNIXTIME(created))
    ORDER BY MONTH(FROM_UNIXTIME(created));
    

    I find it odd that you are adding 1 to the month in the SELECT.

    You can change the WHERE to:

    WHERE created >= UNIX_TIMESTAMP(DATE(CONCAT(YEAR(CURDATE), '-01-01')))
    

    In general, it is a good idea to avoid the use of functions on columns. This is less important when you are selecting a significant number of rows (unless the column is a clustered index).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?