我知道在php部分有很多预订问题。
相信我,当我告诉你,我尝试了大多数,至少那些似乎兼容。所以让我解释一下。
我有预约表
ID | day | start | end |
----------------------------------
1 | 01-01-2018 | 09:00 | 10:00 |
2 | 01-01-2018 | 10:00 | 13:00 |
3 | 02-01-2018 | 12:00 | 15:00 |
4 | 02-01-2018 | 18:00 | 19:30 |
我想知道,使用sql是否有可能得到空的时隙?结果应该类似于:
day | start | end
---------------------------
01-01-2018 | 00:00 | 09:00
01-01-2018 | 13:00 | 23:59
02-01-2018 | 00:00 | 12:00
02-01-2018 | 15:00 | 18:00
02-01-2018 | 19:30 | 23:59
查询应包含两个日期:开始日期+结束日期
我在这里准备了一把小提琴:https://www.db-fiddle.com/f/6dm8q8UtmDkkkjExYfMEbx/1
最佳答案
MSSQL版本
WITH X AS
(
SELECT ROW_NUMBER() OVER (ORDER BY Day, Start)sq, [Day], [Start], [End]
FROM (
SELECT [Day], [Start], [End]
FROM [appointments]
UNION
SELECT Day, '00:00', '00:00'
FROM [appointments]
UNION
SELECT Day, '23:59', '23:59'
FROM [appointments]
) T1
)
SELECT A.Day, A.[End] AS Start, b.[Start] AS End
FROM x A
JOIN x B
ON A.sq = B.sq -1
AND A.[Day] = B.[Day]
AND A.[End] <> b.[Start]
Mysql 5.7版本
SET @RowNumber = 0;
CREATE TABLE cte
SELECT (@RowNumber := @RowNumber+1) AS Rownumber, Day, Start, End
FROM (
SELECT Day, Start, End
FROM booking
UNION
SELECT Day, '00:00', '00:00'
FROM booking
UNION
SELECT Day, '23:59', '23:59'
FROM booking
) T1
ORDER BY day ASC, Start ASC
;
SELECT A.Day, A.End AS Start, B.Start AS End
FROM cte A
JOIN cte B
ON A.Rownumber = B.Rownumber -1
AND A.Day = B.Day
AND A.End <> B.Start
ORDER BY A.Day asc, A.End asc
将添加一个小提琴来演示
https://www.db-fiddle.com/f/6dm8q8UtmDkkkjExYfMEbx/2
MySQL5.7包括无预订天数
SET @RowNumber = 0;
CREATE TABLE cte
SELECT (@RowNumber := @RowNumber+1) AS Rownumber, Day, Start, End
FROM (
SELECT Day, Start, End
FROM booking
UNION
SELECT Day, '00:00', '00:00'
FROM booking
UNION
SELECT Day, '23:59', '23:59'
FROM booking
) T1
ORDER BY day ASC, Start ASC
;
SELECT DAY, Start, End
FROM(
SELECT A.Day, A.End AS Start, B.Start AS End
FROM cte A
JOIN cte B
ON A.Rownumber = B.Rownumber -1
AND A.Day = B.Day
AND A.End <> B.Start
UNION
SELECT DATE_ADD(A.Day, INTERVAL 1 DAY) AS Day, B.Start AS Start, A.End AS End
FROM cte A
JOIN cte B
ON A.Rownumber = B.Rownumber -1
AND A.Day <> B.Day
)Result
ORDER BY Day ASC, Start ASC
https://www.db-fiddle.com/f/6dm8q8UtmDkkkjExYfMEbx/3