嵌套SQL查询 - 逻辑问题

时间:2014-05-09 22:25:19

标签: mysql sql

我在创建SQL查询时遇到了一些问题。

在我的数据库中,我有两个表,房间和预订,表格结构如下:

表:会议室

roomID : int (PK, auto increment, unique)
description : varchar
capacity : int

表:预订

resID : int (PK, auto increment, unique)
roomID : int (FK)
date : date
beginning : time
end : time

现在我想知道是否可以创建一个查询,该查询返回一些关于一些传递参数的房间列表。一个房间不应该同时有两个或两个以上的预订。

简单地说,查询类似于:

SELECT description from rooms 
WHERE capacity is greater or equal to :passedCapacity
AND date not equal to :passedDate
OR date is equal to :passedDate BUT 
:passedBeginning and :passedEnd do not collide with other reservations

我不知道该怎么做。

非常感谢任何帮助。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

如果您想查找所有重叠的预订,那么您需要某种join。但是,您可以使用exists子句执行此操作,如:

select r.*
from reservations r
where exists (select 1
              from reservations r2
              where r2.roomId = r.roomId and
                    r2.date = r.date
                    r2.resid <> r.resid and
                    r2.beginning < r.end and
                    r2.end > r.beginning
             );

这使用了当第一个在第二个结束之前开始而第一个在第二个结束之后结束时两个时间段重叠的逻辑。