我有一个称为会议预定的表,下面是表的结构
会议桌
id | meeting_name | from_time | to_time | date
以下是结构
CREATE TABLE `bookings` (
`id` int(11) NOT NULL,
`meeting_name` varchar(255) DEFAULT NULL,
`from_time` time DEFAULT NULL,
`to_time` time DEFAULT NULL,
`date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `bookings` (`id`, `meeting_name`, `from_time`, `to_time`, `date`) VALUES(
(1, 'meeting1', '09:00:00', '10:30:00', '2018-07-26'),
(2, 'meeting2', '11:40:00', '12:25:00', '2018-07-26');
(3, 'meeting3', '03:40:00', '04:25:00', '2018-07-26'););
,在这里我尝试查找两次之间的可用时间段,假设如果我将from time
输入为10:00:00
,将to time
输入为01:00:00
,则它将返回此之间的所有会议。时间,并且需要找出它们之间的可用时间
我是mysql的新手,所以尝试了几次查询,但没有得到预期的结果
SELECT *
FROM `bookings`
WHERE bookings.from_time>="10:00:00" and bookings.to_time<="01:00:00"
SELECT *
FROM `bookings`
WHERE bookings.from_time>="10:00:00" or
bookings.to_time<="10:00:00" or
bookings.from_time>="01:00:00" or
bookings.to_time<="01:00:00"
预期结果 如果我在10:00:00.00到13:00:00之间经过时间,则应该返回
以及
等可用插槽10:31:00 to 11:39:00
12.26 to 03:49:00
答案 0 :(得分:0)
要在指定的时间段(从10:00h到13:00h)内查找至少有一部分时间的所有会议,
SELECT *
FROM `bookings`
WHERE bookings.from_time<="13:00:00" -- end of time slot
AND bookings.to_time>= "10:00:00" -- start of time slot
我希望我对结束时间有正确的理解。我更喜欢使用24小时表示法。为了完整起见,您还应该检查date
的值是否与调查的时隙相同。
在此处尝试小演示:http://rextester.com/LNUD45826
答案 1 :(得分:0)
首先,我也使用24h格式,
在这里,您的数据又增加了一天,以表明该查询将封装同一天会议之间的间隔:
CREATE TABLE `bookings` (
`id` int(11) NOT NULL,
`meeting_name` varchar(255) DEFAULT NULL,
`from_time` time DEFAULT NULL,
`to_time` time DEFAULT NULL,
`date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `bookings` (`id`, `meeting_name`, `from_time`, `to_time`, `date`) VALUES
(1, 'meeting1', '09:00:00', '10:30:00', '2018-07-25'),
(2, 'meeting2', '11:40:00', '12:25:00', '2018-07-25'),
(3, 'meeting3', '03:40:00', '04:25:00', '2018-07-25'),
(1, 'meeting4', '09:00:00', '10:30:00', '2018-07-26'),
(2, 'meeting5', '11:40:00', '12:25:00', '2018-07-26'),
(3, 'meeting6', '03:40:00', '04:25:00', '2018-07-26');
这是您的查询,使用SQL Server中实现的LAG
函数很容易,在这里我们必须模仿它(here's how to do it-它可以帮助您理解查询)
select @start := cast('10:00:00' as time), @end := cast('13:00:00' as time),
@time := cast(null as time), @date := cast(null as date);
select date, to_time_lag, from_time, gap_between_meetings from (
select id,
meeting_name,
from_time,
@time to_time_lag,
to_time,
@date date_lag,
case when @date = date then timediff(from_time, @time) end gap_between_meetings,
@time := to_time,
date,
@date := date
from bookings
where from_time between @start and @end
or to_time between @start and @end
order by date, from_time
) a where gap_between_meetings is not null