简体   繁体   English

SQL查询返回与当前日期或当月最后一天匹配的行

[英]SQL query to return rows that match current or last day of month

I have a scheduler application in php that runs actions at certain days of the month based on information stored in a "schedules" table. 我在php中有一个调度程序应用程序,该程序基于存储在“调度表”中的信息在每月的某些天运行操作。 Each row is a separate action and one of the columns stores the day of the month to use for scheduling. 每行是一个单独的操作,其中一列存储用于计划的月份中的一天。 The application executes actions every day by cron job. 该应用程序每天通过cron作业执行操作。 The problem I have is if someone defines a schedule to run on the 31st of every month. 我的问题是,是否有人定义了要在每月31号运行的时间表。

This is the query that I am currently using to get the schedules to run for the current day: 这是我当前用于获取当天要运行的计划的查询:

SELECT * FROM schedules WHERE dayOfTheMonth = DAY(CURDATE())

This won't work for months that don't have 31 days but I want to make sure the schedule runs monthly. 这将在没有31天的月份中无法正常工作,但我想确保时间表按月运行。 So it should run on the last day of the month if the stored day exceeds the last day for this month. 因此,如果存储的日期超过了该月的最后一天,它应该在每月的最后一天运行。 Does anyone know an elegant way to do this? 有人知道这样做的优雅方式吗?

SELECT
    *
FROM
    schedules
WHERE
    (
        DAY( CURDATE() ) = DAY( LAST_DAY( CURDATE() ) )
        AND
        dayOfTheMonth > DAY( LAST_DAY( CURDATE() ) )
    )
    OR
    dayOfTheMonth = DAY( CURDATE() )

If the current day is the last day of the month (eg Feb 28), then any schedule set on a day after the 28th (eg 29, 30, 31) will also be selected and returned - otherwise it only matches rows that have an exact day match. 如果当前日期是该月的最后一天(例如2月28日),则也会选择并返回在28号之后的一天(例如29、30、31)设置的任何计划-否则,它仅与包含确切的比赛日。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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