找到免费的时间

时间:2014-04-29 13:22:48

标签: mysql sql database phpmyadmin

这是数据库架构:

   CREATE TABLE `bookings` (
      `id` int(2) NOT NULL,
      `start` time NOT NULL,
      `end` time NOT NULL
    );

    INSERT INTO `bookings` VALUES(1, '13:00:00', '14:30:00');
    INSERT INTO `bookings` VALUES(2, '15:00:00', '16:00:00');

我尝试运行以下查询,以查找'10:00:00'和'18:00:00'之间的空闲时间:

SELECT free_from, free_until
FROM (SELECT a.end AS free_from,
             (SELECT MIN(c.start)
              FROM bookings c
              WHERE c.start>a.end
             ) as free_until
      FROM bookings a
      WHERE NOT EXISTS (SELECT 1
                        FROM bookings b
                        WHERE b.start BETWEEN a.end AND a.end + 1
                       ) AND
            a.end BETWEEN '10:00:00' AND '18:00:00'
     ) t

生成的输出是:

free_from   free_until
14:30:00    15:00:00
16:00:00    NULL

为什么最后会出现NULL?请帮我解决这个问题。预期输出应为:

free_from   free_until
10:00:00    13:00:00
14:30:00    15:00:00
16:00:00    18:00:00

1 个答案:

答案 0 :(得分:1)

要考虑的事情......

SELECT NULL id,NULL start, '09:59:59' end
UNION
SELECT * FROM bookings
UNION
SELECT NULL,'18:00:01',NULL;
+------+----------+----------+
| id   | start    | end      |
+------+----------+----------+
| NULL | NULL     | 09:59:59 |
|    1 | 13:00:00 | 14:30:00 |
|    2 | 15:00:00 | 16:00:00 |
| NULL | 18:00:01 | NULL     |
+------+----------+----------+