我有一个存储过程,它将两个表联合起来,每个表有1.5M行数据。为默认搜索字段(VARCHAR(255)
)创建了全文索引,并在select / where子句中创建了包含列名称的非聚集索引。
同时应用分页并仅从两者中获取必要的列 表。
UNION
用于组合表后我想要不同的记录。
查询的响应时间从3秒到超过一分钟不等。当过滤器文本只包含两个字符时,它太慢,在重复执行时仍然可以更快地获取值。
DECLARE @start INT, @length INT, @searchQuery VARCHAR(100) --Param
DECLARE @sortQuery VARCHAR(100)
SET @sortQuery = @searchQuery;
SET @searchQuery = ('"' + @searchQuery + '*"');
SELECT temp2.*
, t3.Name AS CountryName
, t5.Name AS CityName
, t4.Name AS StateProvinceName
, t4.Code AS StateProvinceCode
FROM
(SELECT temp1.* FROM
(SELECT ID
, Name
, ISNULL(Address1, '') AS AddressLine1
, ISNULL(Address2, '') AS AddressLine2
, ISNULL(CityID, 0) AS CityID
, ISNULL(CountryID, 0) AS CountryID
, ISNULL(StateProvinceID, 0) AS StateProvinceID
, ISNULL(PostalCode, '') AS PostalCode
FROM Table1
WHERE Deleted= 0 AND CONTAINS(Name, @searchQuery)
UNION
SELECT t2.EmployerID AS ID
, t2.DivisionName AS Name
, t2.Address1 AS AddressLine1
, t2.Address2 AS AddressLine2
, t2.CityID AS CityID
, t2.CountryID AS CountryID
, t2.StateProvinceID AS StateProvinceID
, t2.PostalCode AS PostalCode
FROM Table2 t2
JOIN Employer t1 ON t2.EmployerID = t1.ID
WHERE t2.Deleted= 0 AND t2.DivisionName IS NOT NULL AND t2.DivisionName <> ''
AND t1.Deleted = 0 AND t2.CountryID IS NOT NULL AND t2.Address1 IS NOT NULL AND t2.Address2 IS NOT NULL
AND CONTAINS(t2.DivisionName, @searchQuery)
) temp1
ORDER BY (CASE WHEN temp1.Name LIKE @sortQuery +'%' THEN 2 ELSE 1 END) DESC, temp1.Name
OFFSET @start ROWS
FETCH NEXT @length ROWS ONLY
) temp2
JOIN Table3 t3 ON C.ID = temp2.CountryID
JOIN Table4 t4 ON S.ID = temp2.StateProvinceID
JOIN Table5 t5 ON Ct.ID = temp2.CityID
ORDER BY temp2.Name