有一张表table1、其中一个字段为sort_type
想查询table1表。当sort_type = 5时如果有记录取出,
如果sort_type = 5 没有记录则查询sort_type = 3 时的记录。
请问这样的条件怎么写sql 语句啊?请高手指教,非常感谢!!

解决方案 »

  1.   

    select * from table1 where sort_type = 5
    union all
    select * from table1 where sort_type = 3
           and not exists (select 1 from table1 where sort_type = 5)
      

  2.   

    SQL> select * from t;       AAA        BBB
    ---------- ----------
             1          2
             3          4
             5          6
             1          1已用时间:  00: 00: 00.20
    SQL> select * from t where (exists(select 1 from t where aaa=5) and aaa=5) 
      2  or (not exists(select 1 from t where aaa=5) and aaa=3);       AAA        BBB
    ---------- ----------
             5          6已用时间:  00: 00: 00.10
    SQL> delete from t where aaa=5;已删除 1 行。已用时间:  00: 00: 00.70
    SQL> select * from t where (exists(select 1 from t where aaa=5) and aaa=5) 
      2  or (not exists(select 1 from t where aaa=5) and aaa=3);       AAA        BBB
    ---------- ----------
             3          4已用时间:  00: 00: 00.10
    SQL>
      

  3.   

    select * from t where sort_type=nvl((select max(sort_type) from t where sort_type=5),3)
      

  4.   

    select * from t where sort_type=nvl((select max(sort_type) from t where sort_type=5),3)
      

  5.   

    select * from tablel where sort_type=decode((select max(sort_type) from tablel where sort_type=5),5,5,3)