根据条件加入?

Join based on condition?

是否可以根据条件来调节 join

例如,如果 @DoJointrue,则执行 inner join。它会取代这样的东西:

declare @DoJoin bit = 1

if @DoJoin = 1
BEGIN 
    select T.* from T inner join L on T.col = L.col
END
ELSE 
BEGIN
    select T.* from T
END
DECLARE @DoJoin BIT = 1

SELECT
    T.*
FROM 
    T LEFT JOIN L ON T.col = L.col
WHERE
    --Optional INNER/LEFT JOIN  
    (
        --LEFT JOIN 
        @DoJoin = 0
        OR
        --INNER JOIN
        (
            -- only return rows from T where they have a record in L
            @DoJoin = 1 
            AND 
            L.col IS NOT NULL
        )
    )

如果我了解您的数据可能如何工作,您可能根本不需要连接,因为您只是将连接用作过滤器。因此,如果是这种情况,您可以只执行此操作,并且只进行一个查询。

select T.* from T 
where @DoJoin = 0 or exists(SELECT * FROM L where L.col = T.col)