mysql last month date statement

后端 未结 2 1605
我在风中等你
我在风中等你 2020-12-16 01:12

I have a DATE, how do I write a where that checks for last month until now (either the first of or just today\'s day -1 month)?

相关标签:
2条回答
  • 2020-12-16 01:13

    Actually, last month until now would be:

    From the beginning of the month:

    SELECT * FROM table
    WHERE date >= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-01')
    AND date <= NOW()
    

    Since a month ago: (hopefully you have no future dates on the table)

    SELECT * FROM table
    WHERE date >= (CURRENT_DATE - INTERVAL 1 MONTH)
    

    Alternatively, you might want only the last month... Say today is September and you want all August, not including any of September... That is what I understand as 'last month'.

    SELECT * FROM table
    WHERE date >= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01')
    AND date < DATE_FORMAT(CURRENT_DATE, '%Y/%m/01')
    

    You could also do for the same result:

    SELECT * FROM table
    WHERE YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
    AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
    
    0 讨论(0)
  • 2020-12-16 01:28
    SELECT * FROM table WHERE dateField > DATE_SUB(NOW(), INTERVAL 1 MONTH)
    

    This selects all rows that have a dateField more recent than current timestamp minus one month (so, for example, given today is 26 Sep 2009 00:56 it would give rows that are more recent than 26 Aug 2009 00:56)

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