在我的应用程序中,我有一个用户订购的约会,表格如下:
id simTypeID simID simDateTime startHour endHour
1 100 1 2016-09-01 09:00:00 09:00:00 10:00:00
2 100 2 2016-09-01 10:00:00 10:00:00 11:00:00
3 100 3 2016-09-01 11:00:00 11:00:00 12:00:00
4 100 1 2016-10-11 10:00:00 10:00:00 11:00:00
*注意:开始时间是每天上午9:00
现在我想通过 simID
获取特定日期(例如2016-09-01)的所有空闲时间这意味着结果需要在tbl_free_time:
simID startFreeHour endFreeHour
1 10:00:00 23:59:00
2 09:00:00 09:59:00
2 11:00:00 23:59:00
3 09:00:00 10:59:00
3 12:00:00 23:59:00
如何在同一张桌子上使用TIMEDIFF? (需要采取第一行的endHour和第二行的startHour)。
任何其他方式来解决这个问题将不胜感激!
我正在考虑用以下方法创建temp tbl:
CREATE TABLE tbl_sim_temp LIKE tbl_sim
INSERT tbl_sim_temp
SELECT * FROM tbl_sim
WHERE simDateTime BETWEEN '2016-09-01 00:00:00' AND '2016-09-01 23:59:59'
ORDER BY id ASC
而不是使用 LEFT JOIN ,类似的东西 -
SELECT TIMEDIFF(a.startHour,b.endHour)
FROM a tbl_sim
LEFT JOIN b tbl_sim_temp
WHERE a.simID = b.simID AND a.simTypeid = b.simtypeid AND a.id = b.id+1
但我被困了
答案 0 :(得分:0)
这是我的答案。
SELECT simID, startFreeHour, endFreeHour
FROM (
SELECT simID, "09:00:00" as startFreeHour, SUBTIME(startHour, '00:01:00') as endFreeHour
FROM tbl_sim
WHERE
startHour > "09:00:00"
AND DATE(simDateTime) = "2016-09-01"
UNION
SELECT simID, endHour as startFreeHour, "23:59:00" as endFreeHour
FROM tbl_sim
WHERE
endHour < "23:59:00"
AND DATE(simDateTime) = "2016-09-01"
) as t1
ORDER BY simID ASC, startFreeHour ASC
只有当一天只有一行并且simId并且假设秒将始终为零以限制为23:59:00时,它才有效。因此,这种情况不起作用:
id simTypeID simID simDateTime startHour endHour
1 100 1 2016-09-01 09:00:00 10:00:00 11:00:00
1 100 1 2016-09-01 09:00:00 12:00:00 13:00:00
如果这种情况可以告诉我,我会再试一次。