0

我有一个 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 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 为空,但如果第一个没有结果集,我只想让这个选择生效...

任何想法表示赞赏。谢谢!

4

1 回答 1

0

我认为最好的方法是同时使用它们,如果第一个没有返回行,则运行第二个。但是,如果您需要进行一个查询,请尝试在 Oracle 中使用 WITH 子句。我猜你使用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 列中不存在的唯一值。

于 2013-08-09T16:37:06.263 回答