Oracle:从一个表中选择两个不同的行,如果任何条目不存在,则从另一个表中选择值

时间:2016-09-09 11:51:12

标签: oracle join

这是两张桌子。我想选择TABLE1的创建时间为type =' PENDINGTIMESTAMP'并输入=' DISTRIBUTEDTIMESTAMP'对于TABLE2ID。

TABLE1
+------+--------+--------------------+-------------------+
|ID    |TABLE2ID|TYPE                |CREATED            |
+------+--------+--------------------+-------------------+
|156174|849118  |PENDINGTIMESTAMP    |2016-09-09 03:33:11|
|156175|849118  |DISTRIBUTEDTIMESTAMP|2016-09-09 03:33:11|
|156176|849118  |PROCESSTIME         |2016-09-09 03:33:11|
|156177|849119  |DISTRIBUTEDTIMESTAMP|2016-09-09 03:33:11|
|156178|849119  |PROCESSTIME         |2016-09-09 03:33:11|
+------+--------+--------------------+-------------------+
TABLE2
+------+-------------------+
|ID    |CREATED            |
+------+-------------------+
|849118|2016-09-09 05:00:00|
|849119|2016-09-09 06:00:00|
+------+-------------------+

If any of the entry not exist in TABLE1 for TABLE2ID then i want select created time of TABLE2.CREATED where TABLE2.ID 

Final Result would be
+--------+-------------------+-------------------+
|TABLE2ID|TIME1              |TIME2              |
+--------+-------------------+-------------------+
|849118  |2016-09-09 03:33:11|2016-09-09 03:33:01|
|849119  |2016-09-09 06:00:00|2016-09-09 03:33:01|
+--------+-------------------+-------------------+
For Highlighted entry -> Entry not exist in TABLE1 and created timestamp taken from TABLE2

TIME1 in the second row should be taken from TABLE2

我试过像下面这样的想法。它正在做笛卡尔积并返回两行

select
table2.id table2id,
case when t2.logtype = 'PENDINGTIMESTAMP' then t2.created else table2.created end as time1,
case when t1.logtype = 'NEWTIMESTAMP' then t1.created else table2.created end as time2
from
table2,
table1 t1,
table1 t2
where
table2.id(+) = t1.table2id
and table2.id(+) = t2.table2id

1 个答案:

答案 0 :(得分:0)

我现在假设,table2包含每个可能的table2id。

所以我将从table2到table1创建2个外连接,一个用于挂起,一个用于分布式时间戳。

最后,在选择时我们可以使用NVL函数将创建的时间戳用作后备值。

SELECT m.id AS table2id,
       NVL(p.created, m.created) AS time1,
       NVL(d.created, m.created) AS time2
FROM   table2 m
       LEFT OUTER JOIN table1 p ON (p.table2id = m.id AND p.type = 'PENDINGTIMESTAMP')
       LEFT OUTER JOIN table1 d ON (d.table2id = m.id AND d.type = 'DISTRIBUTEDTIMESTAMP')

或使用Oracle外连接语法(我不确定IS NULL是否真的需要补偿丢失的行):

SELECT m.id AS table2id,
       NVL(p.created, m.created) AS time1,
       NVL(d.created, m.created) AS time2
FROM   table2 m,
       table1 p,
       table1 d
WHERE  m.id = p.table2id(+)
   AND p.type(+) = 'PENDINGTIMESTAMP'
   AND m.id = d.table2id(+)
   AND d.type(+) = 'DISTRIBUTEDTIMESTAMP'

请注意:我没有Oracle System来测试手头的语句,而且我现在还没有使用Oracle SQL语法大约3年。如果有语法错误,请原谅。

但我希望,你明白了。