MySQL在事件发生前7天和事件发生后7天选择

时间:2012-05-14 21:34:45

标签: mysql events

我有数据库,其中包含生日和用户名称日期。我想选择从7天前到7天生日/名字日的所有用户此选择工作,但我不知道如何解决有生日/名字日31.12的用户的问题。例如。 PHP将返回“用户生日前3天”,此选项仅在年底前7天和新年后7天内正常运行。非常感谢您的帮助。

SELECT `name`, `surname`, `gender`, ('birthday') AS event,
  DATEDIFF(NOW(), DATE(REPLACE(`birthday`, YEAR(`birthday`), YEAR(NOW())))) AS diff
FROM `users`
WHERE DATEDIFF(NOW(), DATE(REPLACE(`birthday`, YEAR(`birthday`), YEAR(NOW()))))
BETWEEN -7 AND 7
UNION
  SELECT `name`, `surname`, `gender`, ('namesday') AS event,
    DATEDIFF(NOW(), DATE(REPLACE(`namesday`, YEAR(`namesday`), YEAR(NOW())))) AS diff
  FROM `users`
  WHERE DATEDIFF(NOW(), DATE(REPLACE(`namesday`, YEAR(`namesday`), YEAR(NOW()))))
  BETWEEN -7 AND 7

3 个答案:

答案 0 :(得分:1)

好问题。 这就是我到目前为止所做的。我不确定它是否完美但它可能是一个好的开始。试一试。

select *,
if(right(birthday,5)>=right(curdate(),5),concat(year(curdate()),'-',right(birthday,5)),concat(year(curdate()+interval 1 year),'-',right(birthday,5))) as next_birthday,
if(right(birthday,5)<right(curdate(),5),concat(year(curdate()),'-',right(birthday,5)),concat(year(curdate()-interval 1 year),'-',right(birthday,5))) as prev_birthday
from users
having next_birthday 
between curdate() - interval 7 day and curdate() + interval 7 day
or prev_birthday 
between curdate() - interval 7 day and curdate()

答案 1 :(得分:1)

我认为这很简单,使用to_days()。这种方式依赖于数据库中设置的日历,因此您不必担心闰年。

select
    `name`, `surname`, `gender`, ('birthday') AS event,
    to_days(concat(year(current_date()),'-',month(`birthday`), '-',day_of_month(`birthday`))) as current_yr_bday 
FROM `users`
WHERE 
    to_days(concat(year(current_date()),'-',month(`birthday`), '-',day_of_month(`birthday`))) between to_days(date_sub(current_date() interval 7 days) and to_days(date_add(current_date() interval 7 days

答案 2 :(得分:0)

蛮力方法是计算你的差异为YEAR-1,年,年+ 1,然后检查这3个总和中的任何一个是否满足你的条件。

现在和1月1日之间的区别并不是那么蛮力,而是相应地计算年数。

有趣的问题,如果我想到别的话,我会回来的。