MySQL select all rows from last month until (now() - 1 month), for comparative purposes

后端 未结 10 487
北海茫月
北海茫月 2020-12-07 18:12

I need some help writing a MySQL query to show me rows from last month, but not the whole month, only up and until the same day, hour and minute as it is now(), but 1 month

10条回答
  •  轮回少年
    2020-12-07 18:54

    You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.

    select 
      *
    from
      yourtable t
    where
      /* Greater or equal to the start of last month */
      t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
      /* Smaller or equal than one month ago */
      t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)
    

提交回复
热议问题