SQL Server,TimeSpans

时间:2011-10-03 07:19:37

标签: sql

我在查询数据库时遇到了麻烦..我有一张桌子:

**Room**
 +----------------------------------+
 |RoomNo---RoomStatusID---RoomTypeID|
 |  1   ---     1      ---    1     |
 |  2   ---     1      ---    1     |
 +----------------------------------+

**ClientRoom**
 +--------------------------------------------------------------------+
 |ClientRoomNo---RoomNo--------ArrivalDate-------------DepartureDate  |
 |  1         ---  1   ---- 2011-10-03 1:00:00 ---- 2011-10-03 4:00:00|
 |  2         ---  1   ---- 2011-10-03 5:00:00 ---- 2011-10-03 8:00:00|
 +--------------------------------------------------------------------+

如果我使用此查询=

SELECT Room.RoomNo, RoomType.RoomType
FROM Room INNER JOIN
RoomType ON Room.RoomTypeNo = RoomType.RoomTypeNo
FULL OUTER JOIN ClientRoom ON Room.RoomNo = ClientRoom.RoomNo
WHERE
(((ClientRoom.ArrivalDate <= '10-03-2011 1:00:00' AND
ClientRoom.ArrivalDate <= '10-03-2011 5:00:00') AND
(ClientRoom.DepartureDate <= '10-03-2011 1:00:00' AND
ClientRoom.DepartureDate <= '10-03-2011 5:00:00'))
OR Room.RoomStatusId  = 1)

它将返回

**ClientRoom**
     +--------------------------------------------------------------------+
     |ClientRoomNo---RoomNo--------ArrivalDate-------------DepartureDate  |
     |  2         ---  1   ---- 2011-10-03 5:00:00 ---- 2011-10-03 8:00:00|
     +--------------------------------------------------------------------+

因为早上5点到达。 但是当我改变抵达和出发时间为5:00 - 8:00 .. RoomNo 1仍然在结果中。 我已经尝试过没有了:(

1 个答案:

答案 0 :(得分:2)

你没有解释在什么情况下你想要什么结果。但是这个条件

ClientRoom.ArrivalDate <= '10-03-2011 1:00:00' AND 
ClientRoom.ArrivalDate <= '10-03-2011 5:00:00'
看起来很可疑,因为第一部分是多余的。你可以简单地说

    ClientRoom.ArrivalDate <= '10-03-2011 5:00:00'

下一部分也是如此:

ClientRoom.DepartureDate <= '10-03-2011 1:00:00' AND
ClientRoom.DepartureDate <= '10-03-2011 5:00:00'

这就像说:

ClientRoom.DepartureDate <= '10-03-2011 5:00:00'

修改:从我读过的评论中,您有一个给定的时间跨度(a,d)并希望检查每一行,如果您的时间跨度重叠行的时间跨度(A,D)。您希望仅查看不重叠的行。

这意味着你的WHERE子句必须像这个quasicode:

WHERE d <= A -- my departure will be before the rows arrival
   OR a >= D -- my arrival is behind the rows departure

完整地说:

WHERE (    '10-03-2011 5:00:00' <= ClientRoom.ArrivalDate 
        OR '10-03-2011 1:00:00' >=  ClientRoom.DepartureDate 
      )
    OR Room.RoomStatusId = 1

编辑2

此修复的查询是什么? “向我显示所有计划行,这与我的日程表没有冲突。”但查询应该是“向我显示没有任何与我的日程表冲突的房间”。这是一个完全不同的野兽,但很容易翻译成SQL:

SELECT 
    Room.RoomNo
FROM Room
WHERE NOT EXISTS (
    SELECT 1 
    FROM ClientRoom
    WHERE 
       Room.RoomNo = ClientRoom.RoomNo
       AND (   '10-03-2011 5:00:00' <= ClientRoom.ArrivalDate 
            OR '10-03-2011 1:00:00' >=  ClientRoom.DepartureDate 
           )
)
OR Room.RoomStatusId  = 1