2017-05-25 93 views
1

你怎麼能加入一個子查詢本身?我想要做如下的事情。如何將子查詢加入自己?

SELECT 
    four.src AS start, four.dest AS layover, f.dest AS destination 
FROM 
    (SELECT 1 AS src, 2 as dest union all select 2, 3) AS four 
JOIN 
    four AS f 
ON f.src = four.dest 

但是上面的查詢給我的錯誤

消息208,級別16,狀態1,行1 無效對象名 '四'。

我寧願沒有將其保存爲一個變量或查看等第一,因爲這是一個整體的查詢的一部分(這本身就是一個子查詢等一系列UNIONS其一部分),我不想以確保在其他地方沒有影響聯繫。

這個變化背後的力量是four曾經是一個簡單的查找,但現在這個查詢的值必須計算。


PS - 這是一個簡單的例子,在我來說,我four子查詢是幾百行代碼

回答

3

您可以使用CTE在這種情況下。在這裏,您不需要將此結果存儲在任何臨時對象中。

;WITH four AS (
SELECT 1 AS src, 2 as dest 
union all 
select 2, 3 
) 

SELECT F1.src AS start, F1.dest AS layover, f2.dest AS destination 
FROM four F1 
INNER JOIN four F2 ON F1.src = F2.dest 
0

您需要重新編寫一次。你的別名'四'只能在'選擇','在','有','在'等方面被調用。僅作爲條件,並且不作爲連接中的表格,除非它本身是表格名稱

SELECT 
    four.src AS start, four.dest AS layover, f.dest AS destination 
FROM 
    (SELECT 1 AS src, 2 as dest union all select 2, 3) AS four 
JOIN 
    (SELECT 1 AS src, 2 as dest union all select 2, 3) AS f 
ON f.src = four.dest 
0

使用臨時表。

Declare @Temp(src int, desc int); 
INSERT INTO @Temp(src,desc) 
VALUES 
(SELECT 1 AS src, 2 as dest union all select 2, 3) 
SELECT * FROM @Temp t1 
INNER JOIN @Temp t2 ON t1.src = t2.dest 
+0

>我寧願不必將它作爲變量存儲 – ArtB