I have a simple query below to select available assets from a table based on their checkout and expected return date. If the checkout and expected return date overlaps with the @RentStartDate
and @RentEndDate
then I want to select it as UnavailableAsset
. Please see my query below
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);
Now i know that this query works perfectly, but I'm just not sure if there is a better way to write the conditions in the where
clause. Is there a better way to simplify the conditions to make this query more efficient?
Thanks
Based on the description of what you are doing, I don't understand why you think your query works.
The overlap query should look like this:
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE CheckOutDate <= @RentEndDate AND
ExpectedReturnDate >= @RentStartDate;
This type of query can be difficult to optimize (in most databases). You can start with an index on agreementasset(CheckOutDate, ExpectedReturnDate, AssetID)
.
Have you tried using the BETWEEN
keyword?
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE (CheckOutDate BETWEEN @RentStartDate AND @RentEndDate)
OR (ExpectedReturnDate BETWEEN @RentStartDate AND @RentEndDate)
I don't think you can streamline and no duplicate conditions
SELECT AssetID as UnAvailableAsset
FROM agreementasset
WHERE (@RentStartDate <= CheckOutDate AND @RentEndDate >= CheckOutDate)
OR (@RentStartDate >= CheckOutDate AND @RentEndDate <= ExpectedReturnDate)
OR (@RentStartDate <= ExpectedReturnDate AND @RentEndDate >= ExpectedReturnDate);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.