简体   繁体   中英

Mysql Select record based on last run

I have a table which has following fields

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

I want to select those records which are due now based on last_job_run field. For instance, if a task has run yesterday and daily is selected then I need a query to select the record for today, tomorrow and so on.

Is it possible to do it without involving PHP?

Use:

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))

This might run faster as a UNION statement:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM