有了这些数据:
create table rooms
(
orderid int not null,
roomname varchar(8) not null,
date date not null,
`from` time not null,
`to` time not null
);
insert into rooms values (1231, 'E12', '2013-04-05', '07:00', '10:00');
insert into rooms values (1671, 'E12', '2013-04-05', '13:00', '14:00');
要获取可用的时间间隔/时隙,您可以发出以下查询:
SELECT DATE_FORMAT(r1.`to`, '%T') AS `From`, DATE_FORMAT(min(r2.`from`), '%T') AS `To`
FROM
rooms r1 JOIN rooms r2
ON r1.`to`< r2.`from`
WHERE r1.date = '2013-04-05' AND r1.roomname = 'E12'
GROUP BY r1.`to`
HAVING
NOT EXISTS (SELECT NULL FROM rooms r3
WHERE r1.`to` < r3.`to`
AND min(r2.`from`) > r3.`from`)
上面的查询将返回:
10:00:00 13:00:00
这是 SQL 小提琴:http ://sqlfiddle.com/#!2/3c124/25
注意:以上查询由@fthiella改编自此答案:
https://stackoverflow.com/a/14139835/114029
使用此附加查询:
SELECT (COUNT(*) = 0) AS Available
FROM rooms
WHERE roomname = 'E12' AND date = '2013-04-05' AND
(
(`from` < MAKETIME(10,00,00) AND `to` > MAKETIME(10,00,00)) OR
(`from` < MAKETIME(13,00,00) AND `to` > MAKETIME(13,00,00))
)
它将返回,即在给定的开始时间 ( ) 和结束时间 ( )1
之间没有预订,因此房间可用。from
to
这是使用数据的 SQL Fiddle:http ://sqlfiddle.com/#!2/3c124/1