Man*_*ena 9 mysql sql database oracle postgresql
我有一个案例,我必须获取列field1 ='value1'的记录,如果没有'value1'的值,那么我应该获取'默认'的记录.
对于上面的场景,我使用了两个查询:
Select * from table_name where field1="value1"
如果上面的查询没有回复任何记录,我会触发以下查询:
Select * from table_name where field1="default"
现在我想在一个查询中执行上述操作.有人可以帮我一样.我相信答案就在于使用CASE WHEN子句.
此外,上述查询应该适用于oracle,postgres以及mysql.
核心ANSI SQL答案,预计将在所有不同平台上运行:
select * from table_name
where field1 = 'value1'
or (field1 = 'default'
and NOT EXISTS (select 1 from table_name where field1 = 'value1'))
Run Code Online (Sandbox Code Playgroud)
最佳解决方案使用coalesce():
Select * from table_name where field1 = coalesce (
(select field1 from table_name where field1='value1' limit 1)
, 'default'
);
Run Code Online (Sandbox Code Playgroud)
请注意limit 1子查询中的:在这种情况下,必须确保子查询不返回多于一行。但是即使使用此case when exists (...)方法,也最好添加它,因为否则,数据库引擎将被迫扫描与子查询匹配的所有行。
当然,大多数现代数据库都足够智能,可以对其进行静默优化。但是有些旧的不能。无论如何,在某些情况下他们可能无法做到。
也就是说,例如在PostgreSQL中,如果子查询使用非(或未正确声明为)稳定函数,则计划器将被迫执行全面扫描以产生一致的结果(如果该函数有任何副作用)。
使用CASE并存在,如下所示
Select * from table_name where field1=
case when exists(select 1 from table_name where field1='value1')
then 'value1' else 'default 'end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3045 次 |
| 最近记录: |