[英]SQL - Select statements within case
如何使用SQL case语句实现此目的?
select count(*) x from t_table where file_id = 310012;
if x<>0 : select distinct status from t_table where file_id = 310012
else : return x
您可以使用union all
来做您想做的union all
:
select distinct status
from t_table
where file_id = 310012
union all
select 0
from dual
where not exists (select 1 from t_table where tile_id = 320023);
但是,返回具有0
的单行似乎是个坏主意,因为它可能与value status
混淆。
注意:如果status
为字符串,则应使用'0'
。
See the code below:
SELECT CASE COUNT(*)
WHEN COUNT(*) > 0 THEN
(SELECT status FROM t_table WHERE file_id = 310012)
ELSE null END AS x
FROM t_table WHERE file_id = 310012;
您无需计数记录。 只需执行一个查询:
select distinct status from t_table where file_id = 310012
当查询返回某些行时,则x必须为<> 0
如果查询返回空结果集,则x必须等于0,并且if x <> 0 then ..... else return x
获得第二部分, if x <> 0 then ..... else return x
另外,您可以提高处理速度,因为您只对表运行一个查询,而不对两个查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.