2016-12-05 64 views
1

已成立这样列在SQL Server中的子查询

select '1' a, '2' b into #tmp1 
select '3' c, '4' d into #tmp2 

鉴于临时表为什么没有下面的SQL Server提供一个错误?

select * from #tmp1 where a not in (select b from #tmp2) 
+0

你为什么期望它给与错误? – DVT

+3

@DVT因为'b'不是'#tmp2'中的列 – Siyual

+3

主查询中的列可以在子查询中访问。所以在'从#tmp2'选择b时,'b'来自'#tmp1'。 –

回答

3

没有错误,因为主查询中的列可以在子查询中访问。因此,在

select b from #tmp2 

b#tmp1到来。

Here是解释它的文章。

If a column is referenced in a subquery that does not exist in the table referenced by the subquery's FROM clause, but exists in a table referenced by the outer query's FROM clause, the query executes without error. SQL Server implicitly qualifies the column in the subquery with the table name in the outer query.

+2

尽管在这里犯错误很容易,但是以为从子查询中的#tmp2输入了一个有效的列名称。我想这里的教训是始终使用表的别名和选择列时,如'select * from#tmp1 t1 where a not in(从#tmp2 t2选择t2.b)' –