0
SELECT ID, Name
FROM dbo.AmenitiesList 
WHERE TypeID=@Type and Status = 'Available'
    AND ID NOT IN
    (SELECT AmenitiesID FROM dbo.ReservationList
     WHERE Status = 'Cancelled' AND StartDate between @Arrival and @Departure
     or EndDate between @Arrival and @Departure
     or @Arrival between StartDate and EndDate
     or @Departure between StartDate and EndDate)

这是我的查询,我想显示状态为“已取消”且到达日期和离开日期不在数据库中的到达日期和离开日期之间的所有可用设施。但是在检索数据时,我没有得到可用的设施,因为当状态被取消时,它会触发关于日期之间的其他条件。如何避免这种情况?

我想显示已取消且不在 ArrivalDate 和 Departure Date 之间的设施

提前谢谢你们!

4

3 回答 3

1

对于性能和优化,请考虑表变量。

DECLARE @TABLE AS TABLE
(
  AmenityID INT PRIMARY KEY CLUSTERED
)
INSERT INTO @TABLE
SELECT AmenitiesID FROM dbo.ReservationList
--Your conditions

--Get values that exist
SELECT * FROM AmentitiesList al
INNER JOIN @Table t on al.AmenityID = t.AmenityID

--Get values that don't
SELECT * FROM AmentitiesList al
LEFT JOIN @Table t on al.AmenityID = t.AmenityID
WHERE t.AmenityID IS NULL

仅仅因为代码更短,并不意味着它可以扩展。Left Joins也是一种痛苦……

您也可以通过使用表变量轻松摆脱它。

DECLARE @AmenityList AS TABLE
(
  AmenityID INT PRIMARY KEY CLUSTERED
  Matched BIT DEFAULT(0)
)
INSERT INTO @AmenityList
Select AmenityID FROM AmentitiesList

UPDATE @AmenityList SET Matched = 1
FROM @AmenitityList al
INNER JOIN @Table t on t.AmentityID = al.AmentityID

SELECT * FROM @AmentityList WHERE Matched = 0
于 2013-03-04T16:35:30.593 回答
1

这个版本怎么样?

SELECT ID, Name
FROM dbo.AmenitiesList 
WHERE TypeID=@Type and Status = 'Available'
    AND ID NOT IN
    (SELECT AmenitiesID FROM dbo.ReservationList
     WHERE Status = 'Cancelled' AND (StartDate between @Arrival and @Departure
     or EndDate between @Arrival and @Departure
     or @Arrival between StartDate and EndDate
     or @Departure between StartDate and EndDate))
于 2013-03-04T16:35:53.070 回答
0
SELECT ID, Name
FROM dbo.AmenitiesList 
WHERE TypeID=@Type and Status = 'Available'
    AND ID NOT IN
    (SELECT AmenitiesID FROM dbo.ReservationList
 WHERE Status != 'Cancelled' AND Status != 'Check Out' AND  ((@Arrival <= EndDate) AND (@Departure >= StartDate)))

这解决了我的问题!顺便感谢你们花时间向我提供信息!上帝保佑!

于 2013-03-04T17:10:43.797 回答