如何按条件联接表

时间:2018-08-30 08:09:59

标签: sql sql-server

假设我有2个表要加入它们。但是我需要根据参数确定INNER JOIN或LEFT OUTER JOIN。

有什么办法可以做到这一点?

3 个答案:

答案 0 :(得分:3)

您可以尝试一下,不确定性能-我想还可以:

DECLARE @join char(1) = 'L' -- L(eft),R(ight),I(nner)

DECLARE @t1 table(id int)
DECLARE @t2 table(id int)
INSERT @t1 values(1),(2)
INSERT @t2 values(2),(3)

SELECT t1.id t1id, t2.id t2id 
FROM
  @t1 t1
FULL JOIN
  @t2 t2
ON
  t1.id = t2.id
WHERE 
  @join = 'L' and t1.id is not null
  or @join = 'R' and t2.id is not null
  or @join = 'I' and t1.id = t2.id

答案 1 :(得分:1)

您可以声明一个变量,并在JOIN条件下使用该变量。您可以放置​​UNION ALL,以便当结果集之一给出结果集时,您将获得所需的结果集。

DECLARE @isLEFTJOIN bit = 0
SELECT * 
FROM Table1 AS a
LEFT JOIN Table2 AS b
ON a.Id = b.Id
WHERE @isLEFTJOIN = 1
UNION ALL
SELECT * 
FROM Table1 AS a
JOIN Table2 AS b
ON a.Id = b.Id
WHERE @isLEFTJOIN = 0;

答案 2 :(得分:0)

一种选择是使用IF语句:

DECLARE @jointype char(1) = 'L' --(L)EFT JOIN, (R)IGHT JOIN, (I)NNER JOIN

IF @jointype = 'L'    
 Table1 LEFT JOIN Table2 ON Table1.condition = Table2.condition

IF @jointype = 'R'
 Table1 RIGHT JOIN Table2 ON Table1.condition = Table2.condition

IF @jointype = 'I'
 Table1 INNER JOIN Table2 ON Table1.condition = Table2.condition