0

我的数据库中有一个名为 rooms 的表,其中包含房间信息和属性,还有另一个名为 reservation 表的表,其中包含 Room Reserved、FromDate 和 ToDate。

我想要做的是让用户选择他想要预订的房间大小并选择预订房间的日期,然后我根据房间预订表为他提供可用的房间。

我在这里做了什么:

SELECT  * FROM Rooms,Reservations WHERE 
Rooms.R_Size = 'roomSize' AND ('4/19/2013' NOT 
BETWEEN Reservation.FromDate AND Reservation.ToDate  AND '4/19/2013'
NOT BETWEEN Reservation.FromDate AND Reservation.ToDate) 

问题是它返回给我重复的房间,即使它在特定预订的预订日期之间但不是在另一个预订的预订日期之间,它仍然会将它退还给我。

我想要的是检查房间是在同一日期还是在特定日期之间预订,如果是,我根本不希望它被选中并归还。

谢谢..对不起我糟糕的英语

4

2 回答 2

1

What you are doing here is a cross join. Every row from table a (Rooms) is joined with every row in table b (Reservations).

In order to make your query work, you need to specify that Rooms.Rooms_Key = Reservations.Rooms_ForignKey in your where clause (or an explicit join [inner,left,right] and specify the ON fields as they are easier to read in my opinion - explicit-vs-implicit for more info).

Once you have converted the join type, the where clause will start to give you better results, and you should be able to modify it if you still need to at that point.

于 2013-04-17T22:48:36.230 回答
1

您的查询有两个问题。一是房间和预订之间的连接没有条件,这样对于满足日期测试的每个预订,将返回一次正确大小的房间。另一个问题是您的日期测试是错误的,因为它不会检测到完全在新预订日期间隔内的现有预订。

像这样的查询应该会给你你想要的结果:

SELECT * FROM Rooms
LEFT JOIN Reservations 
ON Reservations.R_Number = Rooms.Number
AND Reservations.ToDate > '4/19/2013'
AND Reservations.FromDate < '4/20/2013'
WHERE Rooms.R_Size = 'roomSize' 
AND Reservations.R_Number IS NULL 

它的工作原理是将房间加入到该房间的预订中,然后选择没有与新预订冲突的预订的房间。(旧预订在新预订开始之前结束,或者在新预订之后开始一端没问题)。

于 2013-04-17T22:49:32.937 回答