SQL 服务器子查询会导致性能损失吗?
Do SQL Server subqueries cause performance loss?
我用内连接连接了 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
不需要子查询。您可以通过在列前加上它所属的 table 来解决歧义:
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 提供 别名 它将避免歧义错误。
我用内连接连接了 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
不需要子查询。您可以通过在列前加上它所属的 table 来解决歧义:
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 提供 别名 它将避免歧义错误。