How to get first day of every corresponding month in mysql?

后端 未结 13 1847
野的像风
野的像风 2020-11-27 18:03

I want to get first day of every corresponding month of current year. For example, if user selects \'2010-06-15\', query demands to run from \'2010-06-01\' instead of \'2010

13条回答
  •  情深已故
    2020-11-27 19:09

    There is actually a straightforward solution since the first day of the month is simply today - (day_of_month_in_today - 1):

    select now() - interval (day(now())-1) day
    

    Contrast that with the other methods which are extremely roundabout and indirect.


    Also, since we are not interested in the time component, curdate() is a better (and faster) function than now(). We can also take advantage of subdate()'s 2-arity overload since that is more performant than using interval. So a better solution is:

    select subdate(curdate(), (day(curdate())-1))
    

提交回复
热议问题