这是数据库架构:
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');
我尝试运行以下查询,以查找空闲时间:
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 + INTERVAL your_duration HOURS
) 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
答案 0 :(得分:1)
试试这个:
首先创建表并插入记录
CREATE TABLE bookings (
id int NOT NULL,
start time NOT NULL,
endtime 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');
然后运行此选择查询
SELECT free_from, free_until
FROM (SELECT a.endtime AS free_from,
(SELECT MIN(c.start)
FROM bookings c
WHERE c.start>a.endtime
) as free_until
FROM bookings a
WHERE a.endtime BETWEEN '10:00:00' AND '18:00:00'
) t where free_until IS NOT NULL;
注意:我将您的列结束更改为 endtime
答案 1 :(得分:0)
输出的第一行对应于以下数据集:
a:
1, '13:00:00', '14:30:00'
c:
1, '13:00:00', '14:30:00'
2, '15:00:00', '16:00:00'
对于“free_until”,c.start必须高于a.end,这对于该数据集是满足的。(对于C的第2行)
输出的第二行对应于以下数据集:
a:
2, '15:00:00', '16:00:00'
c:
1, '13:00:00', '14:30:00'
2, '15:00:00', '16:00:00'
表示“free_until”,c.start> a.end但正如您所看到的,a.end在这里是16:00,并且没有c.start高于此值。 这就是为什么null
将第二行的a.end修改为14:00,您将不会获得空值。 :d
修改表格中的数据:
从预订中删除所有内容,然后
INSERT INTO `bookings` VALUES(1, '13:00:00', '14:30:00');
INSERT INTO `bookings` VALUES(2, '15:00:00', '14:00:00');