mySQL SELECT upcoming birthdays

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

    This is my solution. It also works if date of birth is January 1st and today's date is December 31.

    SELECT `id`, `name`, `dateofbirth`,
        DATE_ADD(
            dateofbirth, 
            INTERVAL IF(DAYOFYEAR(dateofbirth) >= DAYOFYEAR(CURDATE()),
                YEAR(CURDATE())-YEAR(dateofbirth),
                YEAR(CURDATE())-YEAR(dateofbirth)+1
            ) YEAR
        ) AS `next_birthday`
    FROM `user` 
    WHERE 
        `dateofbirth` IS NOT NULL
    HAVING 
        `next_birthday` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
    ORDER BY `next_birthday`
    LIMIT 1000;
    

提交回复
热议问题