我有以下两个表
# 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;
而且,正如汤姆所指出的,最好每个通知都有一个已发送的标志,而不是取决于特定的时间。工作可能会因为各种原因而推迟。