如何重写此查询以便更快地执行它?
DECLARE @CityID BIGINT = 89263
-- [ Execution takes 10 sec]
SELECT distinct MHD.[CaxHotelId],[Name],[SupportedAPIS],[Longitude],[Latitude],[CityName],[CountryName]
,[CountryCode],[Star],[HotelChain],[Address],[Telephone],[Fax],[Email],[Website],MHD.[Description],[DisplayName]
INTO #tbl
FROM [MasterHotelData] as MHD
WHERE FK_MasterHotelCityId = @CityID ;
-- OutPut Table 1 [ Execution takes 3 sec, outputs 300 rows ]
SELECT CaxHotelId,Name,SupportedAPIS,Longitude,Latitude,CityName,CountryName,CountryCode,Star
,HotelChain,Address,Telephone,Fax,Email,Website,Description,DisplayName
FROM #tbl;
-- OutPut Table 2 [ Execution takes 30 sec, outputs 3000 rows ]
SELECT [Id]
,MHI.[CaxHotelId]
,CAST ([Url] AS VARCHAR(1000)) -- Original Size VARCHAR(MAX)
,CAST ([ThumbUrl] AS VARCHAR(1000)) -- Original Size VARCHAR(MAX)
,MHI.[UpdatedDate]
FROM [MasterHotelImage] as MHI
INNER JOIN #tbl ON #tbl.CaxHotelId = MHI.CaxHotelId;
-- OutPut Table 3 [ Execution takes 5 sec, outputs 5000 rows ]
SELECT [Id]
,MHA.[CaxHotelId]
,[AmenityName]
,MHA.[Description]
,MHA.[UpdatedDate]
FROM [MasterHotelAmenity] as MHA
INNER JOIN #tbl ON #tbl.CaxHotelId = MHA.CaxHotelId
DROP TABLE #tbl
我已将非群集索引添加到CaxHotelId
和MasterHotelAmenity
的{{1}}。这个查询的总执行时间将近50秒,而我的雇主希望我在10秒内完成执行。
答案 0 :(得分:1)
您是否需要在第一次查询中使用distinct?感觉就像你没有,所以我放弃它。如果确实需要,请尝试使用组。根据我的经验,它们通常要快得多,但这可能取决于数据。
我还要先定义临时表,在CaxHotelId列上放一个索引,然后插入其中。这可能有助于加快你的联接