SQL查询"选择...其中select ..."花太长时间

时间:2014-10-31 11:11:33

标签: sql performance

如何改善此查询的效果?

DECLARE @Form nvarchar(200)
SET @Form=N'mail'

select t1.* from dbo.EDWordForms t1
where t1.CanonicForm in
(
    SELECT CanonicForm 
        FROM  dbo.EDWordForms t2
        WHERE t2.WordForm=@Form)

感谢您的回答,问题解决了 - “CanonicForm”字段上没有索引

3 个答案:

答案 0 :(得分:1)

在许多数据库中,明确的joinexistsin更有效。我会尝试:

select t1.*
from dbo.EDWordForms t1
where EXISTS (SELECT CanonicForm 
              FROM dbo.EDWordForms t2
              WHERE t2.WordForm = @Form AND t1.CanonicForm = t2.CanonicForm
             );

索引也可以帮助查询。对于您的版本(使用in),您需要EDWordForms(WordForm, CanonicForm)上的索引。对于exists(或join)的版本,最佳索引为EDWordForms(CanonicForm, WordForm)

答案 1 :(得分:0)

尝试使用预备声明

DECLARE @execText nvarchar(3000)
DECLARE @Form nvarchar(200)

SET @Form=N'mail'

SET @execText = N'select t1.* from dbo.EDWordForms t1
where t1.CanonicForm in
(
    SELECT CanonicForm 
      FROM  dbo.EDWordForms t2
     WHERE t2.WordForm = '+ @Form + N')'

EXECUTE sp_executesql @execText

答案 2 :(得分:0)

感谢您的回答,问题解决了 - 字段上没有索引" CanonicForm"