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

后端 未结 13 1842
野的像风
野的像风 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 18:57

    You can use DATE_FORMAT() function in order to get the first day of any date field.

    SELECT DATE_FORMAT(CURDATE(),'%Y-%m-01') as FIRST_DAY_CURRENT_MONTH 
    FROM dual;
    

    Change Curdate() with any other Date field like:

    SELECT DATE_FORMAT(purchase_date,'%Y-%m-01') AS FIRST_DAY_SALES_MONTH 
    FROM Company.Sales;
    

    Then, using your own question:

    SELECT *
    FROM
      hrm_attendanceregister
    WHERE
    hrm_attendanceregister.Date) >=
     DATE_FORMAT(CURDATE(),'%Y-%m-01')
    

    You can change CURDATE() with any other given date.

    0 讨论(0)
  • 2020-11-27 19:03

    I'm surprised no one has proposed something akin to this (I do not know how performant it is):

    CONCAT_WS('-', YEAR(CURDATE()), MONTH(CURDATE()), '1')
    

    Additional date operations could be performed to remove formatting, if necessary

    0 讨论(0)
  • 2020-11-27 19:04
    date_add(subdate(curdate(), interval day(?) day), interval 1 day)
    

    change the ? for the corresponding date

    0 讨论(0)
  • 2020-11-27 19:05

    Is this what you are looking for:

    select CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE);
    
    0 讨论(0)
  • 2020-11-27 19:06
    select big.* from
    (select @date := '2010-06-15')var
    straight_join 
    (select * from your_table where date_column >= concat(year(@date),'-',month(@date),'-01'))big;
    

    This will not create a full table scan.

    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题