sql查询重叠时间

时间:2017-09-09 14:41:06

标签: php mysql sql sql-server

enter image description here

我有一个班级预订名称book的表格。 我还有一个包含空间数据的表,称为room

我正试图制作一个条件,如果房间已经预订了特定的时间段,例如上午08:00到上午9:00 - 你不能预订课程。但如果没有那么你可以。

我的sql是:

SELECT * FROM book WHERE room_id = '$room_id' and start_date = '$date' and start_time = '$starttime' BETWEEN (SELECT MIN(start_time) AS mintime
FROM book WHERE room_id = '$room_id' and start_date = '$date') and (SELECT MAX(end_time) AS maxtime
FROM book WHERE room_id = '$room_id' and start_date = '$date')

如果sql返回一行,则用户无法预订房间。

有时这个sql有效,但有时会失败。 我在这做什么是对的?

1 个答案:

答案 0 :(得分:1)

如果以可读格式写出查询,通常会有所帮助:

SELECT * 
FROM book 
WHERE room_id = '$room_id' AND
      start_date = '$date' AND
      start_time = '$starttime' 
BETWEEN (SELECT MIN(start_time) AS mintime
         FROM book 
         WHERE room_id = '$room_id' AND 
               start_date = '$date') AND
        (SELECT MAX(end_time) AS maxtime
         FROM book 
         WHERE room_id = '$room_id' AND
               start_date = '$date')

现在您可以清楚地看到您只使用一个表,即book但只有两个子查询。这似乎有点多,你没有以正确的方式使用BETWEEN。为什么不这样查询:

SELECT * 
FROM book 
WHERE room_id = '$room_id' AND
      start_date = '$date' AND
      '$starttime' BETWEEN start_time AND end_time

我当然应该warn about SQL-injection