如何进行两个表之间的完整结果的外部联接

时间:2019-05-15 13:54:30

标签: sql oracle

我有两个表:

TABLE1

{'Category': ['item1', 'item2', 'item3'], 'Freq': [71984.0, 8129.0, 3140.0]}

TABLE2

id_attr
-------
1
2
3

结果,我想要一个显示以下内容的表:

结果

id  |  id_attr  | val
----------------------
10  |  1        | A
10  |  2        | B

因此,当TABLE2中缺少id_Attr = 3时,我也希望id = 10和id_attr = 3的行(我知道这是因为在RESULT的val列中有NULL值(或其他值)。

注意:我可以在表2中添加其他ID。例如,将以下行插入到table2:{11,1,A}中,作为结果,我想要:

id  |  id_attr  | val
----------------------
10  |  1        | A
10  |  2        | B
10  |  3        | NULL

因此,对于每个id,我都希望始终与所有id_attr匹配。

3 个答案:

答案 0 :(得分:1)

您的特定示例只有一个id,因此您可以使用以下代码:

select t2.id, t2.id_attr, t2.val
from table2 t2
union all
select 10, t1.id_attr, NULL
from table1 t1
where not exists (select 1 from table2 t2 where t2.id_attr = t1.id_attr);

编辑:

您可以通过以下方式获取属性和ID的所有组合。使用cross join创建所需的所有行,然后使用left join引入所需的数据:

select i.id, t1.id_attr, t2.val
from (select distinct id from table2) i cross join
     table1 t1 left join
     table2 t2
     on t2.id = i.id and t2.id_attr = t1.id_attr;

答案 1 :(得分:-1)

这是您可以获得的最接近的东西:

SELECT id,Table1.id_attr,表1中的val

左外连接Table2 ON Table1.id_attr = Table2.id_attr

我认为您不会有

当根据您提供的信息不存在任何关系时,

id = 10和id_attr = 3加入表。

除非有另一个我们不知道的联接

答案 2 :(得分:-2)

听起来您只想对id_attr进行外部联接,而不要对id进行联接。

select * from table2 t2
    left outer join table1 t1 on t2.id_attr = t1.id_attr;