我想加快下面的查询
WHERE子句中有两个条件(引用下面的查询)
目前,大约需要 60 秒。但是,如果我删除 where 子句中的第一个条件(@Query 为 NULL),它几乎会立即返回。
关于如何加快速度的任何想法?表中大约有 70 万行,而且只会增长。
(注意:下面显示的查询被剥离到它的本质,我严格使用硬编码值来简化查询,以便将焦点吸引到上面概述的部分)
declare @Query nvarchar(255)
select @Query = 'oceans'
select
*
from
(select
row_number() over( order by b.BookTitle) as RowNumber,
b.*
from
Books b (nolock)
where
-- If I remove this first condition "@Query is NULL", then it returns almost immediately
-- Otherwise if I keep this here, it takes around 1 minute
-- Yes, I have full-text index on BookTitle, as well as a regular index.
(@Query is NULL) or (contains(b.BookTitle, @Query))
) as t1
where t1.RowNumber between 40 and 60
最佳答案
你能把它分成两个查询吗? or
通常会给优化器带来问题:
if @Query is null
begin
select *
from (select row_number() over( order by b.BookTitle) as RowNumber, b.*
from Books b (nolock)
where @Query is NULL
) as t1
where t1.RowNumber between 40 and 60;
end
else
begin
select *
from (select row_number() over( order by b.BookTitle) as RowNumber, b.*
from Books b (nolock)
where contains(b.BookTitle, @Query)
) as t1
where t1.RowNumber between 40 and 60;
end
关于SQL Server - 与 NULL 相比非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194253/