编写此查询的更好方法

时间:2014-07-21 20:20:52

标签: sql-server tsql query-performance

我想知道我是否可以用连接替换下面的内容并减少ISNULL缠绕整个选择的需要?

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

1 个答案:

答案 0 :(得分: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在Users和UserCompany中是唯一的。