2012-10-19 80 views
0

from中的Transact SQL語句Select語句是什麼意思?select語句中的select語句是什麼意思?

我的意思是這樣

.. from ( 
    select .. 
) 

另外,我需要知道,如果語句是壞的性能。您能否在Transact SQL中爲我提供有關此主題的官方文檔的鏈接?

+2

有時稱爲嵌套SELECT,或子查詢,或可能是臨時表,甚至內聯視圖。如果您發佈整個查詢,則可能可以獲得有關使用更多常規聯接的版本的幫助。 – Randy

+1

「官方」文檔:[子查詢基礎知識](http://msdn.microsoft.com/en-us/library/ms189575.aspx)。處理[相關子查詢](http://msdn.microsoft.com/zh-cn/library/ms187638.aspx)時,您經常遇到性能問題。 –

+0

問題中給出的例子實際上是一個「派生表」,而不是子查詢。 –

回答

0

你會發現很多的信息,這與快速搜尋。例如,參見 Subquery Fundamentals從MSDN

子查詢是嵌套在SELECT,INSERT,UPDATE內, 或DELETE語句,或其它子查詢內的查詢。子查詢可以是 在任何允許使用表達式的地方使用。

+1

爲什麼downvote? – RedFilter

3

參見this link on MSDN about Subquery Fundamentals

子查詢可以很好,但要警告他們沒有編入索引。如果查詢的外部部分必須加入子查詢的結果,性能可能會受到影響。請注意,查詢優化器也可能爲您的查詢選擇不同的執行順序,因此即使您從子查詢「開始」,優化器也可能在其他位置啓動查詢並加入到您的子查詢中。

Correlated Subqueries(Joe Stefanelli首先在上面的註釋中鏈接到這裏)是另一個性能問題。任何時候你有一個查詢必須重複執行一次外部查詢的結果,性能將會受到影響。

看到這個link about Common Table Expressions (CTEs)。 CTE可能是編寫查詢的更好方法。子查詢的其他替代方案包括@table variables和。

子查詢的最常見用法之一是更新表時。 UPDATE語句的SET列表中不能有聚合函數。您必須計算子查詢中的聚合,然後再回到主查詢來更新表。例如:

-- A table of state and the total sales per state 
declare @States table 
(
    ID varchar(2) primary key, 
    totalSales decimal(10,2) 
) 

-- Individual sales per state 
declare @Sales table 
(
    salesKey int identity(1,1) primary key, 
    stateID varchar(2), 
    sales decimal(10,2) 
) 

-- Generate test data with no sales totalled 
insert into @States (ID, totalSales) 
select 'CA', 0 
union select 'NY', 0 

-- Test sales 
insert into @Sales (stateID, sales) 
select 'CA', 5000 
union select 'NY', 5500 

-- This query will cause an error: 
-- Msg 157, Level 15, State 1, Line 13 
-- An aggregate may not appear in the set list of an UPDATE statement. 
update @States 
set totalSales = SUM(sales) 
from @States 
inner join @Sales on stateID = ID 

-- This query will succeed, because the subquery performs the aggregate 
update @States 
set totalSales = sumOfSales 
from 
(
    select stateID, SUM(sales) as sumOfSales 
    from @Sales 
    group by stateID 
) salesSubQuery 
inner join @States on ID = stateID 

select * from @States 
+0

好的,你能提供一個好的和壞的使用子查詢的例子嗎? –