SQL Server 连接与子查询性能问题

标签 sql sql-server join subquery

我发现在某些情况下,查询类似于

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/

相关文章:

java - java中的嵌套选择

SQL Server 加入和查询问题

SQL 给出错误的结果

mysql - 同时选择、连接和更新

MYSQL INSERT INTO 现有表数据来自 2 个单独的表 ON id

php sql将来自不同数据库的多个表连接在一起

mysql - sql内连接删除

mysql - 查询以获取分类的拆分集

php - SQL 查询应该返回任何结果但没有返回任何结果

c# - 有没有办法用 C# 以编程方式发布 rdl 报告?