Select current months records mysql from timestamp column

前端 未结 10 1993
一整个雨季
一整个雨季 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 15:55
    SELECT [columns] 
    FROM [the_table] 
    WHERE MONTH([date_column]) = MONTH(CURDATE())
    

    Replace the text between [] (including the []) with your data.

    0 讨论(0)
  • 2020-12-05 15:58

    Use this query may this help you,

    Query = "SELECT * FROM <table_name> WHERE MONTH(date_entered) = MONTH(CURDATE())";
    
    0 讨论(0)
  • 2020-12-05 15:58

    try this

    SELECT * FROM table WHERE month(data) = EXTRACT(month FROM (NOW()))
    
    0 讨论(0)
  • 2020-12-05 15:59

    The query below can benefit from the index and no functions applied to the timestamp field for where clause evaluation.

    SELECT * 
    FROM TableName 
    WHERE TimestampField >= 
               (CURDATE() - INTERVAL (DAY(CURDATE())-1) DAY) 
          AND TimestampField <  
               LAST_DAY(CURDATE()) + INTERVAL 1 DAY;
    

    If your timestamp field is time part is truncated, go for this one,

    SELECT * 
    FROM TableName 
    WHERE TimestampField BETWEEN 
               (CURDATE() - INTERVAL (DAY(CURDATE())-1) DAY) 
             AND 
               LAST_DAY(CURDATE());
    
    0 讨论(0)
  • 2020-12-05 16:00

    I think in MySQL here is the simplest method which i have tried and works well, you want to select rows where timestampfield is in this month.

    SELECT * FROM your_table 
    WHERE MONTH(timestampfield)=MONTH(CURRENT_DATE()) AND
    YEAR(timestampfield)=YEAR(CURRENT_DATE());
    

    the above will return all records that the timestampfield is this month in MySQL

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

    If you want indexes to be used, don't apply any function to the column:

    SELECT * 
    FROM tableX
    WHERE `date` >= UNIX_TIMESTAMP((LAST_DAY(NOW())+INTERVAL 1 DAY)-INTERVAL 1 MONTH)
      AND `date` <  UNIX_TIMESTAMP(LAST_DAY(NOW())+INTERVAL 1 DAY) ;
    

    The functions used can be found in MySQL docs: Date and Time functions

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