SQL:合并两个没有笛卡尔积的表

时间:2019-06-19 13:00:45

标签: sql sql-server

我正在尝试将两个具有相同行数的表合并在一起,而不使用成熟的笛卡尔积。从某种意义上说,就像有两列彼此相同长度的列一样,无论顺序如何。

更具体地说,我有两个表。表a:

id  fieldA  commonField
1   foo1    value1
2   foo2    value1
3   foo3    value2
4   foo4    value2

和表b:

id  fieldB  commonField
11  bar1    value1
12  bar2    value1
13  bar3    value2
14  bar4    value2

另请参阅sqlfiddle。我要查询的结果应该是:

id  fieldA  commonField fieldB
1   foo1    value1  bar1
2   foo2    value1  bar2
3   foo3    value2  bar3
4   foo4    value2  bar4

fieldB列在commonField的相同值内的排序并不重要。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

select t1.id, t1.fieldA,t2.fieldB
from
(SELECT a.*, row_number() OVER (order by commonfield) as rn from a) as t1
join (select fieldB, row_number() OVER (order by commonfield) as rn from b) as t2
on t1.rn = t2.rn

答案 1 :(得分:0)

使用SQL Server:

with t1 (rNO, id, fieldA, commonField) as
(
select row_number() over (partition by commonField order by id), id, fieldA, commonField
from a
),
t2 (rNO, id, fieldB, commonField) as
(
select row_number() over (partition by commonField order by id), id, fieldB, commonField
from b
)
select t1.id, t1.fieldA, t1.commonField, t2.fieldB 
from t1
inner join t2 on t1.commonField = t2.commonField and t1.rNo = t2.rNo;

PS:根据您的需要,您可能会寻求完全加入:

with t1 (rNO, id, fieldA, commonField) as
(
select row_number() over (partition by commonField order by id), id, fieldA, commonField
from a
),
t2 (rNO, id, fieldB, commonField) as
(
select row_number() over (partition by commonField order by id), id, fieldB, commonField
from b
)
select coalesce(t1.id, t2.id) as id, t1.fieldA, coalesce(t1.commonField, t2.commonField) as commonField, t2.fieldB 
from t1
full join t2 on t1.commonField = t2.commonField and t1.rNo = t2.rNo;