mySQL SELECT upcoming birthdays

前端 未结 17 677
我寻月下人不归
我寻月下人不归 2020-12-03 11:17

I\'m trying to write a query to select users of a database whose birthdays are in the next 7 days.

I\'ve done a lot of research but I can\'t come up with a working s

17条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 11:54

    While trying to get the list who have their b'days upcoming in a range of time, we can run in to couple of issues.

    When there is a leap year, then there is a chance that the condition you have fails to handle the case of leap years. Next problem could be like today is 2016-12-30 and you need b'days for next 7 days. So the end of the period is in year 2017. Some condition fail in this case. These are very important test cases.

    Most of the fixed in this thread are using the DAYOFYEAR() which fails when you are on a leap year.

    eg.

    DAYOFYEAR('2016-03-01 00:00:00') is 61.
    DAYOFYEAR('2015-03-01 00:00:00') is 60

    Simplest and most easy to understand way is this.

    1. Calculate the next upcoming b'day for a user.
    2. Then check if the day comes in our range.

    This works on leap years and also the range of dates span in two years.

    SELECT  * 
    FROM    `PERSONS` 
    WHERE  
        /* 
           Here we calculate the next coming b'day for user 
           and check if it is between our span 
        */
        CONCAT(IF( 
                CONCAT( YEAR(CURDATE()), substring(`BIRTHDAY`, 5, length(`BIRTHDAY`))) < CURDATE(), 
                YEAR(CURDATE()) + 1, /* Adds an year if already past */
                YEAR(CURDATE())  /* Use this year if it is upcoming */
             ), substring(`BIRTHDAY`, 5, length(`BIRTHDAY`))) 
        BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL @tot DAY)
    

    PS: Also it is the best solution if you want to order these on the basis of the b'days. You just need to add this as a field.

提交回复
热议问题