[英]SQL - OR causes query to run extremely slow
When I combine two conditions in the WHERE clause of my query, it takes well over a minute to run. 当我在查询的WHERE子句中组合两个条件时,要花一分钟多的时间才能运行。 If I split into two different queries, they both run in about 1 second.
如果我分成两个不同的查询,它们都将在大约1秒钟内运行。
Any thoughts? 有什么想法吗? See below:
见下文:
This takes well over a minute 这需要一分钟以上
SELECT
COUNT(b.BookKey)
from
Books b (nolock)
inner join BookPublishCities bp (nolock)
on b.BookKey = bp.BookKey
where
contains(bp.PublishRegionName, @SearchTerm) OR contains(b.BookTitle, @SearchTerm)
Together these are about 1 second 这些加在一起大约是1秒
SELECT
COUNT(b.BookKey)
from
Books b (nolock)
inner join BookPublishCities bp (nolock)
on b.BookKey = bp.BookKey
where
contains(bp.PublishRegionName, @SearchTerm)
-- and...
SELECT
COUNT(b.BookKey)
from
Books b (nolock)
inner join BookPublishCities bp (nolock)
on b.BookKey = bp.BookKey
where
contains(b.BookTitle, @SearchTerm)
I'm just not sure why separate queries are so much faster. 我只是不确定为什么单独的查询会这么快。 Thoughts?
有什么想法吗?
or
can pose a problem for SQL optimizers. or
可能对SQL优化器造成问题。 Usually, this problem arises with join
conditions, but it may also be happening here. 通常,此问题是由于
join
条件引起的,但也可能在这里发生。 Try using union
and see if this is faster: 尝试使用
union
,看看是否更快:
SELECT COUNT(*)
FROM ((SELECT bookkey
FROM BookPublishCities bp (nolock)
WHERE contains(bp.PublishRegionName, @SearchTerm)
) UNION ALL
(SELECT BookKey
FROM Books b (nolock)
WHERE contains(b.BookTitle, @SearchTerm)
)
) b;
Note that I simplified the subqueries. 请注意,我简化了子查询。 The
join
s don't seem necessary given the logic -- although under some circumstances they might be important (for instance, if the joins are used for filtering because book keys are not in both tables). 在
join
小号似乎没有必要给出的逻辑-尽管在某些情况下,他们可能是重要的(例如,如果连接被用于过滤,因为本书键不是两个表中)。
This also might not return exactly the same results, because presumably a title and a region could both match. 这也可能不会返回完全相同的结果,因为大概标题和区域都可以匹配。 This could also generate duplicates in your query, so you might want
count(distinct)
in the outer query. 这也可能在您的查询中生成重复项,因此您可能希望在外部查询中使用
count(distinct)
。
Set SHOWPLAN_ALL on
. Set SHOWPLAN_ALL on
。 Inspect the plan for the combination and compare it to the individuals. 检查组合的计划,并将其与个人进行比较。 You may need to provide some hints to the QEP
您可能需要向QEP提供一些提示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.