How do I get the first day of the week of a date in mysql?

后端 未结 8 1410
猫巷女王i
猫巷女王i 2020-11-30 03:47

Suppose I have 2011-01-03 and I want to get the first of the week, which is sunday, which is 2011-01-02, how do I go about doing that?

The reason is I have this quer

8条回答
  •  有刺的猬
    2020-11-30 04:38

    If you need to handle weeks which start on Mondays, you could also do it that way. First define a custom FIRST_DAY_OF_WEEK function:

    DELIMITER ;;
    CREATE FUNCTION FIRST_DAY_OF_WEEK(day DATE)
    RETURNS DATE DETERMINISTIC
    BEGIN
      RETURN SUBDATE(day, WEEKDAY(day));
    END;;
    DELIMITER ;
    

    And then you could do:

    SELECT FIRST_DAY_OF_WEEK('2011-01-03');
    

    For your information, MySQL provides two different functions to retrieve the first day of a week. There is DAYOFWEEK:

    Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.

    And WEEKDAY:

    Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

提交回复
热议问题