连接两个有时缺少连接值的表

时间:2019-04-05 06:29:04

标签: sql oracle

我有两个表,两个列联接在一起,就像person_idcomponent一样联接它们。一个人可以有多个组成部分,但不同人的组成部分可以相同。

问题在于其中一个表具有所有正确的数据,而另一个表在第二列中缺少一些值。

两个表看起来像这样:

第一张桌子:

+----------+-----------+
| person_id|  component| 
+----------+-----------+
| sth      |   A       |  <-- 
| sth      |   B       |  <-- two components for sth
| sth1     |   A       |  <-- A component for sth1
| sth2     |   A       | 
| sth3     |   B       |  <-- B component for sth3 
+----------+-----------+

请注意,sth1和sth1只有一个组件

第二张表:

+----------+-----------+-------+
| person_id|  component| value |
+----------+-----------+-------+
| sth      |   A       | 1     |
| sth      |   B       | 21    |
| sth1     |   null    | 313   |<--should be matched with A component from sth1
| sth2     |   A       | 2     |
| sth3     |   null    | 12    |<--should be matched with B component from sth3
+----------+-----------+-------+

请注意,这些空值只能与表A的单行匹配。

所以我需要第二个表中的值,但我也需要第一个表将空组件与实际组件进行匹配。如您所见,缺少的组件并不总是相同的。

如果第二张表缺少person_id sth1的组成部分,则第一张表将只有一个ID组成部分 因此,无需简单地选择表B是否在组件上缺少值,就应该与表A的人员ID相匹配。

当然,我不能简单地匹配person id,因为它不知道哪个值匹配哪个组件。

3 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

select a.person_id,a.component,value
from first_table  a
inner join second_Table b on a.person_id=b.person_id and a.component=b.component
union 
select a.person_id,a.component,value
from first_table  a
inner join second_Table b on a.person_id=b.person_id
where b.component is null

答案 1 :(得分:0)

首先,您可以尝试加入人员ID和组件,然后在组件为Null时按人员ID合并加入的输出

Select a.person_id,a.component,b.value 
FROM table1 a
INNER JOIN table2 b
on a.person_id=b.person_id and a.component=b.component

UNION ALL

Select a.person_id,a.component,b.value 
FROM table1 a
INNER JOIN table2 b
on a.person_id=b.person_id 
WHERE component is NULL

答案 2 :(得分:0)

如果我的理解正确,那么这是您使用null作为默认值的问题。如果是这样,我通常用left join s来处理:

select t1.person_id, t1.component,
       coalesce(t2.value, t2default.value) as value
from first_table t1 left join
     second_Table t2
     on t1.person_id = t2.person_id and t1.component = t2.component left join
     secondtable t2default
     on t1.person_id = t2.person_id and
        t2.component is null;

union相比,它有两个优点。首先,它不需要删除重复的值。其次,此逻辑可确保第一个表中的所有行都在结果集中。