我有一张桌子上有人和他们的出生日期。我想按照“直到下一个生日的天数”来选择它们。
我尝试使用DAYOFYEAR()
函数:
SELECT id, DAYOFYEAR(datebirth)-DAYOFYEAR(NOW()) AS daystobd
FROM users ORDER BY daystobd;
但是......如果生日已经过去了,我会得到否定daystobd
。目的是将那些列在最后。
有什么想法吗?
编辑:daystobd应反映下一个生日
之前的实际天数新编辑:
我设法用UNION做到了,但我认为确实有更“优雅”的方式来做到这一点。
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
答案 0 :(得分:2)
比较今天的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());
答案 1 :(得分:0)
如果低于0
,给他们一个重量ORDER BY CASE WHEN datstobd<0 THEN 1 ELSE 0 END,daystobd