我有一个简单的查询:
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秒的时间。
答案 0 :(得分:2)
我将尝试将这些条件移至它们各自的JOIN,然后在WHERE中将其替换为OR Ad.CustomerId IS NOT NULL
之类的条件。这样可以减少联接匹配,并减少必须评估联接条件的中间结果。
或者,由于大多数表中的任何数据均未真正返回结果中,因此我将考虑替换
...
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)
之类的相关子查询