SQL Server不相关的子查询非常慢

时间:2010-12-23 22:49:51

标签: sql-server performance correlated-subquery

我有一个简单的,不相关的子查询,在SQL Server上表现很差。我在阅读执行计划方面不是很有经验,但看起来内部查询对外部查询中的每一行都执行一次,即使结果每次都相同。如何告诉SQL Server只执行一次内部查询?

查询如下所示:

select *
from Record record0_ 
where record0_.RecordTypeFK='c2a0ffa5-d23b-11db-9ea3-000e7f30d6a2' 
and (
    record0_.EntityFK in (
        select record1_.EntityFK 
        from Record record1_
        join RecordTextValue textvalues2_ on record1_.PK=textvalues2_.RecordFK 
        and textvalues2_.FieldFK = '0d323c22-0ec2-11e0-a148-0018f3dde540' 
        and (textvalues2_.Value like 'O%' escape '~')
    )
)

2 个答案:

答案 0 :(得分:0)

您应该可以将其更改为直接加入,这有帮助:

select r.*
from Record r
join (  select record1_.EntityFK 
        from Record record1_
        join RecordTextValue textvalues2_ on record1_.PK=textvalues2_.RecordFK 
        and textvalues2_.FieldFK = '0d323c22-0ec2-11e0-a148-0018f3dde540' 
        and (textvalues2_.Value like 'O%' escape '~')
     ) s on s.EntityFK = r.EntityFK
where r.RecordTypeFK='c2a0ffa5-d23b-11db-9ea3-000e7f30d6a2'

这看起来更明智..(但几乎相同的查询)

select r.*
from Record r
join (  select ri.EntityFK 
        from Record ri
        join RecordTextValue t on ri.PK=t.RecordFK
        where 
            t.FieldFK = '0d323c22-0ec2-11e0-a148-0018f3dde540' 
        and t.Value like 'O%' 
     ) s on s.EntityFK = r.EntityFK
where r.RecordTypeFK='c2a0ffa5-d23b-11db-9ea3-000e7f30d6a2'

答案 1 :(得分:0)

分析您的SQL语句并将其放入数据库引擎优化顾问(2005+)并查看它建议的索引。

我不认为您在确定运行查询的最佳方式时给予SQL Server足够的信任。确保在连接中的字段和where子句中包含索引。

这可能是您查询的替代方法,但可能会运行相同的内容:

select record0_.*
from Record record0_
inner join Record record1_
on record0_.EntityFK = record1_.EntityFK
inner join RecordTextValue textvalues2_ 
on record1_.PK=textvalues2_.RecordFK 
    and textvalues2_.FieldFK = '0d323c22-0ec2-11e0-a148-0018f3dde540' 
    and (textvalues2_.Value like 'O%' escape '~')
where record0_.RecordTypeFK='c2a0ffa5-d23b-11db-9ea3-000e7f30d6a2'