duanke3985 2016-12-30 08:08
浏览 231
已采纳

将当前年份时间戳与mysql存储的时间戳进行比较

I want to return from database just the rows added "this year" (current year). Creation date for each row is stored as a timestamp in a decimal format.

One method that i imagine is to get the timestamp range for current year and then select just the rows that fit this range. I have google it but with no success. Is there a way to compare the given year against that database stored timestamp?

  • 写回答

2条回答 默认 最新

  • doulangbi6869 2016-12-30 08:17
    关注

    The usual pattern is as you describe... comparing the bare column to a range.

    We can use an expression to derive the start and end of the range. In this case, the beginning of the year and beginning of the next year.

    EDIT

    If datatype of creation_date column is DATE, DATETIME, or TIMESTAMP format, then, as an example:

    1. WHERE t.creation_date >= DATE_FORMAT(NOW(),'%Y-01-01') + INTERVAL 0 MONTH
    2. AND t.creation_date < DATE_FORMAT(NOW(),'%Y-01-01') + INTERVAL 12 MONTH

    We can test the expressions with a SELECT statement

    1. SELECT DATE_FORMAT(NOW(),'%Y-01-01') + INTERVAL 0 MONTH AS d1
    2. , DATE_FORMAT(NOW(),'%Y-01-01') + INTERVAL 12 MONTH AS d2

    returns

    1. d1 d2
    2. ---------- ----------
    3. 2016-01-01 2017-01-01

    Doing the comparison on the "bare" column is a pattern that will allow for MySQL to use a range scan operation on a suitable index, if one is available.

    If we were to wrap the column in a function, that would force MySQL to evaluate the function for every row in the table. So I don't recommend this pattern. But as an example:

     WHERE YEAR(t.creation_date) = YEAR(NOW()) 
    

    EDIT

    The edited question says created_date column is stored as a decimal datatype.

    As long as the stored values are canonical (That is, the value of a later date will always compare as "greater than" the value of any earlier date) ...

    then the same pattern applies... compare the bare column to the start and end of the range.

    1. WHERE t.decimal_col >= beginning_of_this_year
    2. AND t.decimal_col < beginning_of_next_year

    Just need to provide decimal values (or expressions that return the decimal values) representing the beginning_of_this_year and beginning_of_next_year.

    Absent a more precise definition of what values are stored, and what dates those values values represent, I can't give a more specific example.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部