如何解决SQL Server 子查询会导致性能损失吗?
我使用内连接连接了 2 个表,但是 2 个表具有同名的列。我使我的查询成为子查询以仅使用所需的列。使用子查询会不会导致速度下降?
注意:我使用了翻译
Select
*
From
(Select
t1.Id,...
From
Table1 as t1
left join
Table2 as t2 on t1.Id = t2.ParentId
--Where
--Id = 123 This Line. Error : Ambiguous column name 'Id'.
) as Foo
where
Id = 123
解决方法
不需要子查询。您可以通过为列添加其所属表的前缀来解决歧义:
select t1.Id,...
from Table1 as t1
left join Table2 as t2 on t2.ParentId = t1.Id
where t1.Id = 123 -- presumably
至于您的原始查询:在此处使用子查询会影响性能吗?我希望像 SQL Server 这样的数据库能够预见将谓词推送到子查询的明显优化。但是您需要比较执行计划以确保。
请注意,如果您确实需要子查询,通常最好预先过滤:
select t1.Id,...
from (select * from Table1 where Id = 123) as t1
left join Table2 as t2 on t2.ParentId = t1.Id
,
在您的查询中,包含 where 条件 的最后一行给出 ID 的别名,这将避免歧义错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。