Mysql根据上次运行选择记录

时间:2010-08-21 23:27:00

标签: php sql mysql

我有一个包含以下字段的表

project_name       VARCHAR (100)
running_frequency  enum ('daily', 'weekly', 'monthly')
last_job_run       DATETIME

我想根据last_job_run字段选择现在到期的记录。例如,如果一个任务昨天运行并且每天都被选中,那么我需要一个查询来选择今天,明天等的记录。

是否可以在不涉及PHP的情况下完成?

1 个答案:

答案 0 :(得分:3)

使用:

SELECT t.*
  FROM TABLE t
 WHERE (     t.running_frequency = 'daily' 
         AND t.last_job_run < CURRENT_DATE)
    OR (     t.running_frequency = 'weekly' 
         AND t.last_job_run <= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))
    OR (     t.running_frequency = 'monthly' 
         AND t.last_job_run <= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH))

这可能会作为UNION语句运行得更快:

SELECT x.*
  FROM TABLE x
 WHERE x.running_frequency = 'daily' 
   AND x.last_job_run < CURRENT_DATE
UNION ALL
SELECT y.*
  FROM TABLE y
 WHERE y.running_frequency = 'weekly' 
   AND y.last_job_run <= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
UNION ALL
SELECT z.*
  FROM TABLE z
 WHERE z.running_frequency = 'monthly' 
   AND z.last_job_run <= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)