2014-07-21 63 views
-1

我想知道如果我可以替換下面的連接,並減少ISNULL包裹整個選擇的需要?寫這個查詢的更好的方法

SELECT ISNULL(
(
SELECT Locale FROM Users WHERE UserGuid = @UserGuid), 
(SELECT Locale FROM Companies WHERE CompanyGuid = 
    (SELECT CompanyGuid FROM UserCompany WHERE UserGuid = @UserGuid) 
)) 

回答

1

我認爲這將是等效的:

SELECT ISNULL(u.Locale, c.Locale) 
FROM Companies c 
INNER JOIN UserCompany uc ON c.CompanyGuid = uc.CompanyGuid 
LEFT OUTER JOIN Users u ON uc.UserGuid = u.UserGuid 
WHERE uc.UserGuid = @UserGuid 

注:此假設UserGuid是在用戶和UserCompany獨特。

+0

我能看到的唯一真正的區別是,即使「@ UserGuid」不匹配任何表中的任何內容,OP的查詢也會始終返回一行。這些重要的,甚至是相關的,我們很難分辨出來...... – RBarryYoung

相關問題