我有以下两张表
# Event table
id title start_date end_date
----------------------------------------------------------
1 Foo 2013-05-06 20:30:00 2013-05-06 22:45:00
2 Bar 2013-06-03 07:40:00 2013-05-06 10:45:00
3 Demo 2013-05-02 00:22:00 2013-05-06 03:45:00
4 Test 2013-07-09 10:56:00 2013-05-06 13:45:00
# Notification table
id event_id mail time type sent
----------------------------------------------------------
1 1 123@example.com 15 minute 0
2 1 234@example.com 01 day 0
3 3 655@example.com 01 week 0
4 4 888@example.com 40 minute 0
5 4 999@example.com 42 minute 1
5 4 987@example.com 30 minute 0
每分钟,cron 作业都会执行一个 PHP 脚本来检查是否应将通知发送到通知表中的电子邮件地址。时间值是应发送提醒的事件开始日期之前的相对时间。
例如,当 cron 作业在 2013-05-06 20:15:00 运行时,应将电子邮件发送到电子邮件地址 123@example.com。还应该考虑发送标志。如果将此设置为 0,则在早于发送日期的情况下也应发送所有通知。例如,当 cron 作业在 2013-07-09 10:26:00 运行时,应将邮件发送到 987@example.com 和 888@example .com。
我的问题是,查询在 mysql 中必须是什么样子才能获取通知以满足上面对实际(now())日期的要求?我尝试过 date_sub但并没有真正成功。非常感谢您的帮助。
最佳答案
据我所知,这个问题有两个部分。一是将不同单位转换为时间比较。另一个是确保只有一个通知发出。
第一个可以通过一个大的 case
语句来处理。第二个可以通过检查时间间隔来处理,而不是不等式:
. . .
from event e join
notification n
on e.id = n.event_id
where (case when n.type = 'minute'
then now() - interval n.time minute <= e.start_date and
now() + interval 1 minute - interval time minute > e.start_date
when n.type = 'day'
then now() - interval n.time day <= e.start_date and
now() + interval 1 minute - interval time day > e.start_date
when n.type = 'week'
then now() - interval 7*n.time day <= e.start_date and
now() + interval 1 minute - interval 7*time day > e.start_date
when n.type = 'month'
then now() - interval n.time month <= e.start_date and
now() + interval 1 minute - interval time month > e.start_date
end) > 0 and sent = 0;
而且,正如 Tom 指出的那样,最好为每个通知设置一个已发送标志,而不是取决于特定时间。作业可能会因各种原因而延迟。
关于php - Mysql相对日期减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18469303/