条件太多时查询慢
Slow query when having too many conditions
我有这个简单的查询:
SELECT distinct top 100 A.[Number]
FROM [Section] AS A
LEFT JOIN [Customers] AS c ON c.ARef = A.Number
LEFT JOIN [Guides] AS G ON G.CustomerId = c.CustomerId
LEFT JOIN [Telephones] AS T ON T.CustomerId = c.CustomerId
LEFT JOIN [Epts] AS E ON E.CustomerId = c.CustomerId
LEFT JOIN [Emails] AS Em ON Em.CustomerId = c.CustomerId
LEFT JOIN [Addresses] AS Ad ON Ad.CustomerId=C.CustomerId
WHERE
A.SaloonId= 400
AND (
A.Number= @term OR c.Surname = @term OR c.FirstName = @term
----
OR Ad.Postcode = @term
OR G.CategoryRef= @term
OR T.PhoneNumber = @term
OR E.Code= @term
OR Em.EmailAddress = @term
)
where 部分中包含的所有字段都具有碎片率非常低的索引。
如果我们执行某个词条的查询,则需要 20 多秒,但如果我删除最后一部分中的任何随机行(“----”之后),则需要不到 1 秒。
我会尝试将这些条件移动到它们各自的 JOIN 中,然后在 WHERE 中用 OR Ad.CustomerId IS NOT NULL
之类的条件替换它们。这将减少连接匹配并减少必须根据这些连接条件评估的中间结果的数量。
或者,由于大多数表中的 none 数据实际上在结果中返回,我会考虑替换
之类的东西
...
LEFT JOIN [Guides] AS G ON G.CustomerId = c.CustomerId
...
WHERE
...
OR G.CategoryRef = @term
和OR c.CustomerId IN (SELECT CustomerId FROM Guides AS G WHERE G.CategoryRef= @term)
如果 A
上的条件显着减少 C
的数量,我什至会考虑使用相关子查询,如 OR EXISTS (SELECT * FROM Guides AS G WHERE G.CategoryRef= @term AND G.CustomerId = C.CustomerId)
我有这个简单的查询:
SELECT distinct top 100 A.[Number]
FROM [Section] AS A
LEFT JOIN [Customers] AS c ON c.ARef = A.Number
LEFT JOIN [Guides] AS G ON G.CustomerId = c.CustomerId
LEFT JOIN [Telephones] AS T ON T.CustomerId = c.CustomerId
LEFT JOIN [Epts] AS E ON E.CustomerId = c.CustomerId
LEFT JOIN [Emails] AS Em ON Em.CustomerId = c.CustomerId
LEFT JOIN [Addresses] AS Ad ON Ad.CustomerId=C.CustomerId
WHERE
A.SaloonId= 400
AND (
A.Number= @term OR c.Surname = @term OR c.FirstName = @term
----
OR Ad.Postcode = @term
OR G.CategoryRef= @term
OR T.PhoneNumber = @term
OR E.Code= @term
OR Em.EmailAddress = @term
)
where 部分中包含的所有字段都具有碎片率非常低的索引。
如果我们执行某个词条的查询,则需要 20 多秒,但如果我删除最后一部分中的任何随机行(“----”之后),则需要不到 1 秒。
我会尝试将这些条件移动到它们各自的 JOIN 中,然后在 WHERE 中用 OR Ad.CustomerId IS NOT NULL
之类的条件替换它们。这将减少连接匹配并减少必须根据这些连接条件评估的中间结果的数量。
或者,由于大多数表中的 none 数据实际上在结果中返回,我会考虑替换
之类的东西...
LEFT JOIN [Guides] AS G ON G.CustomerId = c.CustomerId
...
WHERE
...
OR G.CategoryRef = @term
和OR c.CustomerId IN (SELECT CustomerId FROM Guides AS G WHERE G.CategoryRef= @term)
如果 A
上的条件显着减少 C
的数量,我什至会考虑使用相关子查询,如 OR EXISTS (SELECT * FROM Guides AS G WHERE G.CategoryRef= @term AND G.CustomerId = C.CustomerId)