[英]left join tables, use only one row from left table
我试图在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查询是否有可能达到此回报。
为了防止再次连接重复的行,您需要给它们分配一个数字,然后像这样在此数字上进行连接,几乎可以保证这不会在巨大的表上执行得很好:
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
我认为您只需要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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.