我发现在某些情况下,查询类似于
select
usertable.userid,
(select top 1 name from nametable where userid = usertable.userid) as name
from usertable
where active = 1
在 SS2008R2 中完成的时间比等效的连接查询长一个数量级
select
usertable.userid,
nametable.name
from usertable
left join nametable on nametable.userid = usertable.userid
where usertable.active = 1
其中两个表都已建立索引并且有超过 100k 行。有趣的是,在原始查询中插入一个 top 子句使其性能与连接查询相同:
select
top (select count(*) from usertable where active = 1) usertable.userid,
(select top 1 name from nametable where userid = usertable.userid) as name
from usertable
where active = 1
有人知道为什么原始查询的性能如此糟糕吗?
最佳答案
嗯,查询是不同的 - 除非 userid
列是主键或具有唯一性约束,否则第二个查询可能返回比第一个查询更多的行。
也就是说,假设 userid 是主键/唯一,请尝试删除第一个子查询的 TOP 1
部分:
select
usertable.userid,
(select name from nametable where userid = usertable.userid) as name
from usertable
where active = 1
关于SQL Server 连接与子查询性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7349383/