[英]How to rewrite simple SQL condition for better performance
我下面有一个简单的查询,可根据其结帐和预期退货日期从表中选择可用资产。 如果结帐和预期退货日期与@RentStartDate
和@RentEndDate
重叠,那么我想将其选择为UnavailableAsset
。 请在下面查看我的查询
set @RentStartDate = '2016-10-13';
set @RentEndDate = '2016-10-18';
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE (CheckOutDate >= @RentStartDate AND CheckOutDate <= @RentEndDate)
OR
(ExpectedReturnDate >= @RentStartDate AND ExpectedReturnDate <= @RentEndDate)
OR
(@RentStartDate >= CheckOutDate AND @RentEndDate <= ExpectedReturnDate);
现在,我知道此查询可以完美地运行,但是我不确定是否有更好的方法在where
子句中编写条件。 是否有更好的方法来简化条件以使此查询更有效?
谢谢
根据您所做的描述,我不明白您为什么认为查询有效。
重叠查询应如下所示:
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE CheckOutDate <= @RentEndDate AND
ExpectedReturnDate >= @RentStartDate;
此类查询可能难以优化(在大多数数据库中)。 您可以从agreementasset(CheckOutDate, ExpectedReturnDate, AssetID)
上的索引开始。
您是否尝试过使用BETWEEN
关键字?
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE (CheckOutDate BETWEEN @RentStartDate AND @RentEndDate)
OR (ExpectedReturnDate BETWEEN @RentStartDate AND @RentEndDate)
我认为您无法精简且没有重复条件
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE (@RentStartDate <= CheckOutDate AND @RentEndDate >= CheckOutDate)
OR (@RentStartDate >= CheckOutDate AND @RentEndDate <= ExpectedReturnDate)
OR (@RentStartDate <= ExpectedReturnDate AND @RentEndDate >= ExpectedReturnDate);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.