2016-08-02 64 views
6

我有一个情况,我必须为列field1 ='value1'提取记录,如果没有'value1'的值,那么我应该获取'默认'的记录。如何在'WHERE'子句sql中回退到不同的值?

因为我用了两个查询上面的场景:

Select * from table_name where field1="value1"

如果上面的查询不还给我激活一个查询的任何记录:

Select * from table_name where field1="default"

现在我希望在一个查询中完成上述操作。有人可以帮助我一样。我相信答案在于使用CASE WHEN条款。

另外上面的查询应该适用于oracle,postgres以及mysql。

+4

您使用的是什么rdbms? –

+0

postgres,mysql和oracle – user2713255

回答

3

使用案例,并存像下面

Select * from table_name where field1= 
    case when exists(select 1 from table_name where field1='value1') 
    then 'value1' else 'default 'end 
0

对于MySQL:

SET @a = Select Count(*) from table_name where field1="value1" 
IF @a > 0 Then 
Select 
    * 
from 
    table_name 
where 
    field1="value1" 
ELSE 
Select 
    * 
from 
    table_name 
where 
    field1="default" 
END IF 
6

核心ANSI SQL的答案,预计在所有不同的平台上运行:

select * from table_name 
where field1 = 'value1' 
    or (field1 = 'default' 
     and NOT EXISTS (select 1 from table_name where field1 = 'value1')) 
0

好吧,我尝试了这似乎是工作。

SELECT * FROM table_name WHERE 
CASE 
    WHEN EXISTS(SELECT * FROM table_name WHERE field1='value1') THEN field1= 'value1' 
    ELSE field1='default' 
END 
+0

这不起作用 – TheGameiswar

+0

它正在工作我在postgres中试过。 – user2713255

0

你可以试试这个...

select * table_name where field1="default" 
and not exists (select * from table_name where field1="value1") 
union all 
select * from table_name where field1="value1" 
0

您可以使用case语句count检查。使用coalesce()

select * 
    from table_name 
where coulmn_1 = (case 
     when (select count(1) from dc_date_card where coulmn_1 = value_1) > 0 then 
value_1 
else 
    Default 
    end) 
+0

案例表达,不是陈述。 – jarlh

1

最优解:

Select * from table_name where field1 = coalesce (
    (select field1 from table_name where field1='value1' limit 1) 
    , 'default' 
); 

注意的limit 1在子查询:在这种情况下,必须保证子查询没有返回多行。但是,即使使用case when exists (...)方法,添加它也是一种好的做法,否则可能会强制数据库引擎扫描匹配子查询的所有行。

当然,大多数现代数据库都是智能的,可以默默优化它。但一些老的不能。无论如何,它可能是他们不能的情况。例如,在PostgreSQL中,如果子查询使用非(或非正确声明)稳定函数,则计划程序将被迫执行全面扫描以产生一致的结果,如果该函数具有任何s | ide效果。