左连接表,只使用左表中的一行

时间:2015-09-11 12:05:02

标签: sql sql-server join

我正在尝试在MS SQL中连接两个表,但我只需要连接未使用的行。

示例:

table1              table2
key  -  value  |     key  -  value
1    -  1      |     1    -  1
2    -  2      |     2    -  1
3    -  3      |     3    -  3
4    -  3      |     4    -  4

sql代码

select * from table1
left outer join 
(
    select * from 
    (
        select *, row_number() over(partion by value order by key) as rwno
        from table2
    ) as t2 
    where rwno = 0  -- this eliminates first two rows in table2
) as tab2
on
    table1.key = tab2.value

此查询返回

table1.key  -  table1.value  -  tab2.key  -  tab2.value
1           -  1             -  1         -  1
2           -  2             -  null      -  null
3           -  3             -  3         -  3
4           -  3             -  3         -  3

在此返回中,两次使用table2中的第3行

我需要回答(没有两面性)

table1.key  -  table1.value  -  tab2.key  -  tab2.value
1           -  1             -  1         -  1
2           -  2             -  null      -  null
3           -  3             -  3         -  3
4           -  3             -  null      -  null

是否有可能使用MS SQL查询达到此回报。

2 个答案:

答案 0 :(得分:1)

为了防止再次加入重复的行,你需要为它们分配一个数字并加入这个数字,这几乎可以保证这在一张巨大的桌子上表现不佳:

DECLARE @table1 table([key] int, value int)
DECLARE @table2 table([key] int, value int)

INSERT @table1
VALUES(1,1),(2,2),(3,3),(4,3)

INSERT @table2 VALUES(1,1),(2,1),(3,3),(4,4)

;WITH CTE1 as
(
  SELECT
    *, 
    row_number() over(partition by value order by [key]) secondkey
FROM @table1
), CTE2 as
(
  SELECT *,
  row_number() over(partition by value order by [key]) secondkey
  FROM @table2
)
SELECT 
  CTE1.[key], CTE1.value, CTE2.[key], CTE2.[value]
FROM CTE1
LEFT JOIN
  CTE2
ON 
  CTE1.[key] = CTE2.value 
  and CTE1.secondkey = CTE2.secondkey

结果:

key  value  key  value
1    1      1    1
2    2      NULL NULL
3    3      3    3
4    3      NULL NULL

答案 1 :(得分:0)

我想你只想要left join

select t1.key, t1.value, t2.key, t2.value
from table1 t1 left join
     table2 t2
     on t1.key = t2.key and t1.value = t2.value;

如果您想要table1中的不匹配,请使用full outer join代替left join