SQL Server条件连接而不是WHERE .. IN ..子句

时间:2014-08-16 18:47:11

标签: sql sql-server-2008 tsql join

SELECT A.Name, H.Name as BookedBy
 FROM dbo.vwAllLoads A WITH (NOEXPAND) 
 LEFT JOIN dbo.SystemInfo H 
     ON (A.BookedByUserID = H.GlobalNetUserID) 
 WHERE ((A.CustomerID IN (SELECT UCR.CustomerID
                             FROM dbo.UserCustomerRelations UCR  
                             WHERE UCR.UserID IN 
                                       (SELECT UserID FROM @PodUsers) 
                                OR H.GlobalUserID IN 
                                       (SELECT UserID FROM @PodUsers)))

现在我使用上面的where子句过滤数据。如何使用连接或以更好的方式完成相同的操作?

请帮忙

2 个答案:

答案 0 :(得分:1)

假设您的查询类似于:

select a.*
from a
where A.CustomerID IN (SELECT UCR.CustomerID 
                       FROM dbo.UserCustomerRelations UCR
                       WHERE UCR.UserID IN (SELECT UserID FROM @PodUsers) OR
                             UCR.GlobalNetUserID IN (SELECT UserID FROM @PodUsers)
-----------------------------^ was `H`, I'm assuming is `UCR`
                      )

然后,以下内容应该是使用join s:

的等效查询
select distinct a.*
from a join
     dbo.UserCustomerRelations ucr
     on A.CustomerID = ucr.CustomerID join
     @PodUsers pu
     on ucr.UserId = pu.UserId or ucr.UserId = ucr.GlobalNetUserID = pu.UserId;

如果您知道连接不会产生多行

,则distinct是不必要的

答案 1 :(得分:0)

我猜是这样的:

INNER JOIN [dbo].[UserCustomerRelations] UCR
    ON A.[CustomerID] = UCR.[CustomerID]
INNER JOIN @PodUsers PU
    ON UCR.[CustomerID] = PD.[UserID]
    OR H.[GlobalNetUserID] = PD.[UserID]