Oracle:检查是否存在并映射新列

时间:2018-09-18 21:48:40

标签: sql oracle

想检查table_1table_2是否存在ID,并以此为基础尝试创建新列mapped_valuetable_2拥有大量具有重复ID的记录,并且在索引上还具有唯一索引。

SQL> drop table table_1
Table dropped.
SQL> create table table_1(id varchar2(10),value varchar2(10))
Table created.
SQL> insert into table_1
(select '100','ABC' from dual
union all
select '101','DEF' from dual
union all
select '103','GHI' from dual
)
3 rows created.
SQL> commit
Commit complete.
SQL> select * from table_1

ID         VALUE     
---------- ----------
100        ABC       
101        DEF       
103        GHI       

3 rows selected.
SQL> drop table table_2
Table dropped.
SQL> create table table_2(id varchar2(10),value varchar2(10),day date)
Table created.
SQL> insert into table_2
(select '100','ABC',sysdate from dual
union all
select '100','ABC',sysdate from dual
union all
select '100','ABC',sysdate from dual
union all
select '101','DEF',sysdate from dual
union all
select '101','DEF',sysdate from dual
union all
select '101','DEF',sysdate from dual
)
6 rows created.
SQL> commit
Commit complete.
SQL> select * from table_2

ID         VALUE      DAY      
---------- ---------- ---------
100        ABC        18-SEP-18
100        ABC        18-SEP-18
100        ABC        18-SEP-18
101        DEF        18-SEP-18
101        DEF        18-SEP-18
101        DEF        18-SEP-18

6 rows selected.

在下面尝试,但获得了ids 100 and 101的重复记录。 我知道,不应该使用外部联接,因为有重复项。 我想通过利用table_2上的非唯一索引来获得所需的输出,但没有重复项。 怎么办呢?

SQL> select t1.*,case when t2.id is null then '***EMPTY****' else t2.id end as mapped_value 
from table_1 t1,table_2 t2
where t1.id = t2.id(+)

ID         VALUE      MAPPED_VALUE
---------- ---------- ------------
100        ABC        100         
100        ABC        100         
100        ABC        100         
101        DEF        101         
101        DEF        101         
101        DEF        101         
103        GHI        ***EMPTY****

7 rows selected.

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么EXISTS中的CASE可能就是您想要的。

SELECT t1.id,
       t1.value,
       CASE
         WHEN EXISTS (SELECT *
                             FROM table_2 t2
                             WHERE t2.id = t1.id) THEN
           t1.id
         ELSE
           '***EMPTY***'
       END mapped_value
       FROM table_1 t1;
相关问题