一尘不染

显示记录,即使它不存在

sql

所以我有这张表

Col1    Col2    Col3
A       34       X
B       43       L
A       36       L

现在,如果我查询

select * from Table1 where col1 in ('A','B','C')

我期待类似的东西

Col1    Col2    Col3
A       34       X
B       43       L
A       36       L
C       -        -

是否有可能 ?

PS:-C行中的内容仅表示该列为空。


阅读 98

收藏
2021-05-16

共1个答案

一尘不染

您可以创建一个嵌套表架构对象类型:

create type T_List1 as table of varchar2(100);

然后按以下方式构造查询:

 select s.column_value            as col1
      , nvl(to_char(t.col2), '-') as col2
      , nvl(col3, '-')            as col3
  from Table1 t
 right join table(T_List1('A', 'B', 'C')) s
    on (t.col1 = s.column_value)

例子:

-- sample of data from your question
with Table1(Col1, Col2, Col3) as(
  select 'A',  34,  'X' from dual union all
  select 'B',  43,  'L' from dual union all
  select 'A',  36,  'L' from dual
)  -- actual query
 select s.column_value            as col1
      , nvl(to_char(t.col2), '-') as col2
      , nvl(col3, '-')            as col3
   from Table1 t
  right join table(T_List1('A', 'B', 'C')) s --< here list your values
     on (t.col1 = s.column_value)            -- as you would using `IN` clause

结果:

COL1  COL2   COL3
------------------------
A     36     L    
A     34     X    
B     43     L    
C     -      -
2021-05-16