如果第一个选择为空,则仅选择此项

时间:2013-08-09 16:05:14

标签: sql select refactoring isnull

我有一个SQL选择:

select t1.val1, t1.val2
  from table1 t1
 where t1.active = 1
   and t1.col1 =
       (select t2.col1
          from tabl2 t2
         where to_char(t2.id) = to_char('225'))
   and t1.col2 =
       (select t2.col2
          from tabl2 t2
         where to_char(t2.id) = to_char('225'))
  and t1.col3 = (
        select t4.col3
        from table2 t2, 
        table3 t3,
        table4 t4
        where to_char(t2.id) = to_char('225'))
        and t2.t1_id = t1.id
        and t2.t3_id = t3.id
        )

如果整个select为null,我想选择它:

select t1.val1, t1.val2
  from table1 t1
 where t1.active = 1
   and t1.col1 =
       (select t2.col1
          from tabl2 t2
         where to_char(t2.id) = to_char('225'))
   and t1.col2 =
       (select t2.col2
          from tabl2 t2
         where to_char(t2.id) = to_char('225'))
  and t1.col3 is null

看起来,第二个选择只有一个差异t1.col3为空,但我只想在第一个没有结果集时使这个选择生效...

任何想法都赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是使用它们并运行第二个,如果第一个没有返回任何行。 但是,如果您需要进行一个查询,请使用WITH clause in Oracle.尝试使用Oracle?:

WITH T100 as
(
select t1.val1, t1.val2,t1.col3 
  from table1 t1
 where t1.active = 1
   and t1.col1 =
       (select t2.col1
          from tabl2 t2
         where to_char(t2.id) = to_char('225'))
   and t1.col2 =
       (select t2.col2
          from tabl2 t2
         where to_char(t2.id) = to_char('225'))
  and 
  (
   (t1.col3 = (
        select t4.col3
        from table2 t2, 
        table3 t3,
        table4 t4
        where to_char(t2.id) = to_char('225'))
        and t2.t1_id = t1.id
        and t2.t3_id = t3.id
        )
   ) 
   OR t1.col3 IS NULL 
  ) 
)

select val1, val2 
from T100 
where NVL(col3,XXXXXXXX) = NVL((select max(col3) from T100),XXXXXXXX)

XXXXXXXX是Col3列中不存在的唯一值。