检查是否采用了时间段/预订

时间:2013-01-29 15:45:54

标签: sql logic

编辑:Gordon发布的查询似乎有问题。如果我从10-12预订,似乎认为所有预订都在12点以后无效,但所有预订在上午10点之前都有效。

一些快速而简单的想法最终导致我创建了以下查询:

SELECT serverip 
        FROM   server 
        WHERE  serverip NOT IN (SELECT serverip 
                                FROM   booking 
                                WHERE  startat >= datehere 
                                AND expiresat <= datehere) 
        LIMIT  1; 

假设预订表存储以下内容:

+-----------+-----------+----------+----------+-----------+
| bookingid | serverip  | username | startat  | expiresat |
+-----------+-----------+----------+----------+-----------+
|         1 | 127.0.0.1 | testuser | 10:00    | 12:00     |
+-----------+-----------+----------+----------+-----------+

如果用户要为预订输入以下数据:

startat = 9:59
expiresat = 12:01

他们可以轻松绕过我的支票,看看预订时间是否可以根据以前的预订存储。

有关如何更好地解决此问题的任何建议?

我希望 NOT 来限制用户输入,并希望避免硬编码特定的时间段,如果这不是问题,但我会坚持我所拥有的。

感谢您的时间。

3 个答案:

答案 0 :(得分:5)

您需要更改重叠的逻辑。试试这个:

SELECT serverip 
FROM  server 
WHERE serverip NOT IN (SELECT serverip 
                       FROM booking 
                       WHERE startat <= USEREXPIREDATE AND
                             expiresat >= USERSTARTDATE
                      ) 
LIMIT  1; 

当一个插槽在所需的用户到期日期之前开始并在所需的用户开始日期之后结束时,它将被占用。

答案 1 :(得分:1)

SELECT *
FROM server
WHERE serverip NOT IN
(SELECT serverip 
 FROM booking
 WHERE
   (startat <= '2013-01-30 08:00:00' AND expiresat >= '2013-01-30 08:00:00') OR
   (startat <= '2013-01-30 09:00:00' AND expiresat >= '2013-01-30 09:00:00') OR
   (startat >= '2013-01-30 08:00:00' AND expiresat <= '2013-01-30 09:00:00'))

其中8:00是开始时间,9:00到期。

答案 2 :(得分:0)

时间as this pic says 有四种可能性,图片中代表的代码是

SELECT Id FROM reservations 
WHERE 
((start_at < @start_at AND start_at < @end_at) AND (end_at > @start_at AND end_at < @end_at))
OR((start_at > @start_at AND start_at < @end_at) AND (end_at > @start_at AND end_at > @end_at))
OR((start_at <= @start_at AND start_at <= @end_at) AND (end_at >= @start_at AND end_at >= @end_at))
OR((start_at >= @start_at AND start_at <= @end_at) AND (end_at >= @start_at AND end_at <= @end_at))