0

我有以下两张表

# 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.com888@example.com发送邮件。

我的问题是,查询在 mysql 中的外观如何才能获取通知以满足实际 (now()) 日期的上述要求?我尝试使用date_sub但并没有真正成功。非常感谢您的帮助。

4

1 回答 1

1

据我所知,这个问题有两个部分。一是将不同的单位转换为时间比较。另一种是确保只发出一个通知。

第一个可以通过大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;

而且,正如汤姆指出的那样,最好为每个通知设置一个已发送标志,而不是取决于特定时间。工作可能因各种原因而延迟。

于 2013-08-27T15:18:42.137 回答