如果存在行,则选择列,否则在oracle中存在默认值

时间:2017-01-27 05:21:44

标签: sql oracle

在Oracle sql中,我想从表中选择几个列值。如果不存在行,我想为每列选择默认值。我需要类似下面的内容

if exists (select 1 from mytable where key ='11') 
then
select key, value, comment from mytable where key ='11'
else
select 'key1' as "key", 'value1' as "value", 'default' as "comment"

在oracle中执行此操作的最佳方式是什么。

2 个答案:

答案 0 :(得分:2)

试试这个:

select
    key,value,comment
from mytable
where key = '11'
union all
select 'key1', 'value1', 'default' from dual
where not exists (select 1 from mytable where key = '11')

答案 1 :(得分:0)

WITH defaults ( key, value, comment ) AS (
  SELECT 'key1', 'value1', 'Default' FROM DUAL UNION ALL
  SELECT 'key2', 'value2', 'Default' FROM DUAL UNION ALL
  SELECT 'key3', 'value3', 'Default' FROM DUAL UNION ALL
  SELECT 'key4', 'value4', 'Default' FROM DUAL
)
SELECT COALESCE( t.key,     d.key     ) AS key,
       COALESCE( t.value,   d.value   ) AS value,
       COALESCE( t.comment, d.comment ) AS comment
FROM   defaults d
       FULL OUTER JOIN
       your_table t
       ON ( t.key = d.key );