已成立這樣列在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)
已成立這樣列在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)
沒有錯誤,因爲主查詢中的列可以在子查詢中訪問。因此,在
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.
儘管在這裏犯錯誤很容易,但是以爲從子查詢中的#tmp2輸入了一個有效的列名稱。我想這裏的教訓是始終使用表的別名和選擇列時,如'select * from#tmp1 t1 where a not in(從#tmp2 t2選擇t2.b)' –
你爲什麼期望它給與錯誤? – DVT
@DVT因爲'b'不是'#tmp2'中的列 – Siyual
主查詢中的列可以在子查詢中訪問。所以在'從#tmp2'選擇b時,'b'來自'#tmp1'。 –