简体   繁体   English

MySQL / PHP查询-检查输入的开始/结束日期不与Db中的现有日期范围重叠

[英]MySQL / PHP Query - check that entered start/end dates don't overlap existing date ranges in Db

I think this should be simpler than my head is treating it - but I've been staring at it for too long... 我认为这应该比我的头脑要简单得多-但我盯着它看了太久了...

I have a database driven competitions engine for a client. 我有一个针对客户的数据库驱动的竞赛引擎。 They can log in and upload a prize photo, question, start / end dates etc. 他们可以登录并上传奖品照片,问题,开始/结束日期等。

All works great - except they're now changing the system to allow only one competition to be running at a time. 一切都很顺利-只是他们现在正在更改系统,一次只允许进行一场比赛。 So when someone tries to add a new one I need to validate it doesn't overlap with any other competitions already in the database... 因此,当有人尝试添加新的比赛时,我需要验证它与数据库中已有的其他比赛没有重叠...

My head has managed to get me this far : 我的头设法使我走了这么远:

$db->query('SELECT
    1 
FROM
    ' . DB_T_PREFIX . 'competition
WHERE
    (
        start_date <= "'.$fldStartDate->getValue().'"
    AND
        close_date >= "'.$fldStartDate->getValue().'"
    )
AND
    deleted = "0000-00-00 00:00:00"');

Can someone sanity check me that this should cover any overlaps? 有人可以理智地检查我是否应该涵盖所有重叠之处吗? I'm pretty sure I need more conditions to cover this but head has turned to mush... hate working with date ranges. 我敢肯定,我需要更多条件来解决这个问题,但头脑已经变得糊涂了……讨厌使用日期范围。

Thanks, 谢谢,

Steve 史蒂夫

I wrote a scheduling application once that did something like that. 我曾经写过一个调度应用程序,它做了类似的事情。 I used the query below: 我使用下面的查询:

$query = "SELECT ... WHERE ((a.start_time < '$start' AND a.end_time > '$start') OR (a.start_time > '$start' AND a.end_time < '$end')) AND i.user_id=$userId";

$start is the new event's start time, $end is the end time for the new event. $start是新事件的开始时间, $end是新事件的结束时间。 Also make sure that $start and $end are formatted as 'Ymd H:i:s' 还要确保$start$end的格式为'Ymd H:i:s'

Painting time related things is often helpfull: 绘画与时间有关的东西通常是有帮助的:

Timeline ( |------| is one competition; |.......| is "free" time)

Schedule:
...|-----------|.........|-------------------|......|--------|....>
         X                         Y                    Z
You want to create a new Competition:
...................|-------------|................................>
                         NEW

As you can see this timeframe intersects with the Y competition. 如您所见,该时间范围与Y竞争相交。 In order to find each intersecting competition check this in DB (pseudocode): 为了找到每个相交的比赛,请在DB(伪代码)中进行检查:

SELECT 1 FROM x WHERE
  start_date < new_start_date AND end_date > new start_date //intersect left
  OR
  start_date < new_end_date   AND end_date > new_end_date //intersect right

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

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