2015-03-03 59 views
0

我有類似下面的兩個表:TSQL加入替換工會

檔案表

 
Id | ServiceId | AccessLevel 
---------------------------- 
1 | 123  | 1 
2 | 123  | 1 
3 | 123  | 2 

附加檔案表(簡檔是一個外鍵Profile.Id)

 
Id | ProfileId | AccessLevel 
---------------------------- 
1 | 1   | 2 
2 | 1   | 3 
3 | 2   | 2 
4 | 3   | 3 

我目前有一個視圖,在這兩個表上做一個UNION ALL,以便我可以查詢它「簡檔= 1」,得到以下結果集:

 
ProfileId | ServiceId | AccessLevel 
----------------------------------- 
1   | 123  | 1 
1   | 123  | 2 
1   | 123  | 3 

這似乎是很慢的。

所以,我想知道如果/如何我可以得到這個相同的結果集使用單個查詢,但我正在努力找出一種方法來做到這一點。

任何幫助,將不勝感激。視圖後面

查詢:

SELECT Id, ServiceId, AccessLevel FROM Profile 
UNION ALL 
SELECT P.Id, P.ServiceId, A.AccessLevel 
FROM Profile P 
INNER JOIN AdditionalProfile A ON A.ProfileId = P.Id 

每個表包含約160,000條記錄。

+0

需要全部外部連接(如果有任何表是空的)。我猜想聯盟全部更好...你確定它很慢?!? – jarlh 2015-03-03 11:55:27

+0

是啊,它似乎是 – kmcoulson 2015-03-03 12:00:27

+2

如果您的查詢和查詢計劃,查詢計劃數量等查詢緩慢,沒有人可以幫助您根據所提供的信息對其進行優化。 – 2015-03-03 12:43:36

回答

0
SELECT p1.Id, p1.ServiceId, COALESCE(p2.AccessLevel, p1.AccessLevel) 
    FROM Profile p1 
    left join AdditionalProfile p2 
    on p2.ProfileId = p1.Id 
    and p2.AccessLevel <> p1.AccessLevel 

能使用ISNULL而不是COALESCE

用(正常)觀點的問題則沒有索引

更重要的是使之成爲一個存儲過程
如果Id和簡檔被索引此將吸菸快速

SELECT p1.Id, p1.ServiceId, ISNULL(p2.AccessLevel, p1.AccessLevel) 
    FROM Profile p1 
    left join AdditionalProfile p2 
    on p2.ProfileId = p1.Id 
    and p2.AccessLevel <> p1.AccessLevel 
where p1.ID = @ID 

OK嘗試

SELECT p1.Id, p1.ServiceId, COALESCE(p2.AccessLevel, p1.AccessLevel) 
    FROM Profile p1 
outer join AdditionalProfile p2 
    on p2.ProfileId = p1.Id 
+0

嗨,感謝您的回覆,但這不起作用。它只會從AdditionalProfile表中返回記錄。 – kmcoulson 2015-03-03 17:00:55

+0

@kmcoulson不,它不僅僅返回AdditionalProfile記錄。左連接返回左側的所有行 - 這是左連接的作用。 – Paparazzi 2015-03-03 17:17:21

+0

對不起,再解釋一下。我需要來自Profile的記錄和來自AdditionalProfile的記錄(即來自Profile的1行,來自AdditionalProfile的2行,共3行)。您的建議將只會從AdditionalProfile表中返回「AccessLevel」值,除非該表中沒有記錄,那麼它將從Profile中返回「AccessLevel」值。 – kmcoulson 2015-03-03 18:47:36