使用公共主键连接两个表,但引入导致笛卡尔的附加列

Joining two tables with common primary key but bring in additional columns that is causing cartesian

我正在尝试连接两个类似于下面的表。是否可以在没有笛卡尔积的情况下连接和获取数据?

非常感谢任何帮助,谢谢!

Table 1 :主键列:Field2 : R1 : C1 : R1 : C2 : R2 : C3

Table 2 :主键列:Field3 : R1 : O1 :R1:O2 : R3 : O3

Table 3 - 已加入 :第 1 列:第 2 列:第 3 列 : R1 : C1 : 01 : R1 : C2 : 02 : R2 : C3 : : R3 : : 03

这是一种选择;阅读代码中的注释。

示例数据:

SQL> with
  2  t1 (pk, field2) as
  3    (select 'R1', 'C1' from dual union all
  4     select 'R1', 'C2' from dual union all
  5     select 'R2', 'C3' from dual
  6    ),
  7  t2 (pk, field3) as
  8    (select 'R1', '01' from dual union all
  9     select 'R1', '02' from dual union all
 10     select 'R3', '03' from dual
 11    ),

查询从这里开始:

 12  --
 13  -- Calculate row number; that new - RN - column will be then used as supplemental JOIN
 14  -- condition
 15  t1_new as
 16    (select pk, field2,
 17            row_number() over (partition by pk order by field2) rn
 18     from t1
 19    ),
 20  t2_new as
 21    (select pk, field3,
 22            row_number() over (partition by pk order by field3) rn
 23     from t2
 24    ),
 25  -- all PK values, as your final result should contain all of them so you can't just
 26  -- use table1 or table2 as none of them contains all PK values
 27  all_pks as
 28    (select pk, rn from t1_new
 29     union
 30     select pk, rn from t2_new
 31    )
 32  -- finally:
 33  select p.pk, a.field2, b.field3
 34  from all_pks p left join t1_new a on a.pk = p.pk and a.rn = p.rn
 35                 left join t2_new b on b.pk = p.pk and b.rn = p.rn
 36  order by p.pk, a.field2, b.field3;

PK FIELD2     FIELD3
-- ---------- ----------
R1 C1         01
R1 C2         02
R2 C3
R3            03

SQL>