在制定 MYSQL 查询以获得不在表数据内的结果方面需要一些逻辑帮助。
我有一个名为 schedule 的表,其中包含数据类型为“时间”的列,这些列指示该特定时间表的开始和结束时间,以及一个引用表“rooms”的外键,该表将在其中进行。在其搜索功能的 php 代码中,我想添加一个功能来显示当前未被预定占用或空置的房间的结果。我添加了一个 jquery slider 来专门获取搜索者想要的开始时间和结束时间。
TABLE 'schedule'
room sched_start sched_end
1 09:00:00 10:00:00
1 11:00:00 12:00:00
2 07:30:00 08:30:00
2 11:30:00 13:00:00
例如,搜索者想在 10:00:00 到 11:00:00 之间搜索一个空房间。根据数据库,结果应该显示房间 1 和房间 2 应该显示在搜索结果中,因为这两个房间在搜索者指定的时间内都不会被占用。我想按时间顺序比较所有类似房间的时间表,第一行或第一个时间表的'sched_end'和后续行或时间表的sched_start等等,以确定是否有空闲时间之间。谁能帮我解决这个问题?
所有帮助和讨厌的人都将不胜感激,因为我可以在 MySQL 中尽可能多地成为菜鸟。
DROP TABLE IF EXISTS schedule;
CREATE TABLE schedule
(room INT NOT NULL
,schedule_start TIME NOT NULL
,schedule_end TIME NOT NULL
,PRIMARY KEY(room,schedule_start)
);
INSERT INTO schedule VALUES
(1,'09:00:00','10:00:00'),
(1,'11:00:00','12:00:00'),
(2,'07:30:00','08:30:00'),
(2,'11:30:00','13:00:00'),
(3,'09:30:00','10:30:00'),
(3,'11:00:00','12:00:00'),
(4,'10:30:00','10:45:00');
SET @start:= '10:00:00';
SET @end:= '11:00:00';
SELECT DISTINCT x.room
-- or whatever columns you want from whichever table you want
FROM schedule x
LEFT
JOIN schedule y
ON y.room = x.room
AND y.schedule_start < @end
AND y.schedule_end > @start
-- other tables can join in here
WHERE y.room IS NULL;
+------+
| room |
+------+
| 1 |
| 2 |
+------+
http://sqlfiddle.com/#!9/1b677/1
只是为了证明@M0rtiis 的解决方案是错误的...
SELECT DISTINCT room
FROM schedule
WHERE @end <= schedule_start
OR @start >= schedule_end;
+------+
| room |
+------+
| 1 |
| 2 |
| 3 |
+------+