我有一张桌子,上面有人和他们的出生日期。我想按“下一个生日前的天数”来选择它们。
我试过使用DAYOFYEAR()
函数:
SELECT id, DAYOFYEAR(datebirth)-DAYOFYEAR(NOW()) AS daystobd
FROM users ORDER BY daystobd;
但是。。。如果今年过了生日,我就得阴性。其目的是让那些人在最后列出。
知道吗?
编辑:daystobd应该反映下一个生日之前的实际天数
新编辑:
我设法与工会合作,但我想肯定有一种更“优雅”的方式来做到这一点。
SELECT id, DAYOFYEAR(datebirth)-DAYOFYEAR(CURDATE()) AS daystobd
FROM users WHERE DAYOFYEAR(datebirth)-DAYOFYEAR(CURDATE())>=0
UNION
SELECT id, 365+DAYOFYEAR(datebirth)-DAYOFYEAR(CURDATE()) AS daystobd
FROM users WHERE DAYOFYEAR(datebirth)-DAYOFYEAR(CURDATE())<0 ORDER BY daystobd
最佳答案
比较今天的MMDD和用户的生日。然后根据当前或明年相应地构建下一个生日。
SELECT
id,
next_birthday,
DATEDIFF(next_birthday, NOW()) AS daystobd
FROM
(
SELECT
id,
datebirth,
CASE WHEN DATE_FORMAT(datebirth, '%m%d') >= DATE_FORMAT(NOW(), '%m%d')
THEN CONCAT(EXTRACT(YEAR FROM NOW()), '-', DATE_FORMAT(datebirth, '%m-%d'))
ELSE CONCAT(EXTRACT(YEAR FROM NOW()) + 1, '-', DATE_FORMAT(datebirth, '%m-%d'))
END AS next_birthday
FROM users
) data
ORDER BY DATEDIFF(next_birthday, NOW());