mySQL SELECT upcoming birthdays

前端 未结 17 631
我寻月下人不归
我寻月下人不归 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

    I found this code to work really well:

    DATE_ADD(user_birthdate, INTERVAL YEAR(FROM_DAYS(DATEDIFF(CURDATE(), user_birthdate)-1)) + 1 YEAR) AS next_birthday 
    

    it actually really simple, it calculate the person age, then the current's year birthday and then add 1 year.

    it based on the answer of Robert Eisele which you may find here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

    p.s.

    with this solution you might fetch people who had a birthday yesterday (that's because the -1 in the FROM_DAYS calculation, but it is needed because of the leap years). this shouldn't consider you too much since you only want 7 days a head so you should just add the following condition:

    HAVING next_birthday BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY) 
    

提交回复
热议问题