SQL中的if-else子句

时间:2013-07-03 10:00:11

标签: sql plsql

有没有办法在没有PL / SQL的情况下为这样的请求创建查询:

if (select count(column) from table = 0)
then select column1, column2, column 3 from table where condition1
else select column1, column2, column 3 from table where condition2

3 个答案:

答案 0 :(得分:1)

select column1, column2, column3 
  from table 
 where (condition1 and (select count(column) from table) = 0)
    or (condition2 and (select count(column) from table) != 0)

答案 1 :(得分:0)

SQL = SELECT QUERY;

if(Column != 0)
{
     SELECT QUERY;
}
if(Column2 != 0)
{
     SELECT QUERY;
}

当你不添加else语句时它应该有用。

答案 2 :(得分:0)

你可以使用两个LEFT JOINS和COALESCE(这里,我使用column1> 2 / column1< = 2作为condition1和condition2):

with 
  v1 as (select count(column4) as c4_cnt from table1),
  v_cond1 as (select column1, column2, column3 from table1 where column1 > 2),
  v_cond2 as (select column1, column2, column3 from table1 where column1 <= 2)
select 
  v1.*, 
  coalesce(v_cond1.column1, v_cond2.column1) as column1,  
  coalesce(v_cond1.column2, v_cond2.column2) as column2,
  coalesce(v_cond1.column3, v_cond2.column3) as column3
from v1
left join v_cond1 on v1.c4_cnt = 0
left join v_cond2 on v1.c4_cnt != 0