Select current months records mysql from timestamp column

前端 未结 10 1994
一整个雨季
一整个雨季 2020-12-05 15:31

I have a mysql DB that has a TIMESTAMP field titled date. How can I select all fields where the month is the current month?

Thanks in advance!

相关标签:
10条回答
  • 2020-12-05 16:17

    In my opinion, the following is more readable than the accepted answer...

    SELECT id, FROM_UNIXTIME(timestampfield) timestamp 
    FROM table1
    WHERE timestampfield >= DATE_FORMAT(NOW(), '%Y-%m-01')
    

    Note: This would select any records from the next month as well. That usually doesn't matter, because none have been created.

    0 讨论(0)
  • 2020-12-05 16:18
    SELECT 'data of your choice '
    FROM 'your table'
    WHERE
    MONTH'datecolumn'=MONTH(CURRENT_DATE )
    

    replace text in ' ' with appropriate from your database

    0 讨论(0)
  • 2020-12-05 16:19

    As of 2020, you can use BETWEEN to handle the query from the very beginning.

    SELECT *
    FROM [TABLE]
    WHERE [DATE_FIELD] 
    BETWEEN 
    CAST('2020-30-01' AS DATE) AND CAST('2020-10-31' AS DATE);
    

    I know is not the most "automatic" way, but from a SQL perspective it is very friendly and straightforward.

    Source https://www.techonthenet.com/mysql/between.php

    0 讨论(0)
  • 2020-12-05 16:21

    UPDATE

    A much better index-friendly way to query your data for a range of dates

    SELECT id, FROM_UNIXTIME(timestampfield) timestamp 
      FROM table1
     WHERE timestampfield >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH)
       AND timestampfield <  UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY);
    

    Note: You don't apply any function to your column data, but rather do all necessary calculations on the right side of the conditions (which are constants and are evaluated only once post-execution). This way you allow MySQL to benefit from index(es) that you might have on the timestampfield column.

    Original answer:

    SELECT id, FROM_UNIXTIME(timestampfield) timestamp 
      FROM table1
     WHERE MONTH(FROM_UNIXTIME(timestampfield)) = MONTH(CURDATE())
       AND YEAR(FROM_UNIXTIME(timestampfield)) = YEAR(CURDATE())
    

    Note: Although this query produces the correct results it effectively invalidates the proper usage of the index(es) that you might have on the timestampfield column (meaning MySQL will be forced to perform a fullscan)

    Here is SQLFiddle demo

    0 讨论(0)
提交回复
热议问题