一个)
select decode(count(*), 0, 'N', 'Y') rec_exists
from (select 'X'
from dual
where exists (select 'X'
from sales
where sales_type = 'Accessories'));
Run Code Online (Sandbox Code Playgroud)
B)
select decode(count(*), 0, 'N', 'Y') rec_exists
from (select 'X'
from sales
where sales_type = 'Accessories');
Run Code Online (Sandbox Code Playgroud)
C)其他(指定)
编辑:很难选择"正确"的答案,因为最佳方法取决于在检查值是否存在后您想要做什么,如APC指出的那样.我最终选择了RedFilter的答案,因为我最初设想这个检查本身就是一个功能.
Red*_*ter 76
select case
when exists (select 1
from sales
where sales_type = 'Accessories')
then 'Y'
else 'N'
end as rec_exists
from dual;
Run Code Online (Sandbox Code Playgroud)
APC*_*APC 14
您想要实现的基础逻辑是什么?例如,如果您想测试是否存在记录以确定要插入或更新,那么更好的选择是使用MERGE.
如果您希望记录大多数时间都存在,那么这可能是最有效的处理方式(尽管CASE WHEN EXISTS解决方案可能同样有效):
begin
select null into dummy
from sales
where sales_type = 'Accessories'
and rownum = 1;
-- do things here when record exists
....
exception
when no_data_found then
-- do things here when record doesn't exists
.....
end;
Run Code Online (Sandbox Code Playgroud)
如果SALES_TYPE不是唯一的,您只需要ROWNUM行.当你想要知道的是否至少存在一条记录时,进行计数毫无意义.
select count(1) into existence
from sales where sales_type = 'Accessories' and rownum=1;
Run Code Online (Sandbox Code Playgroud)
Oracle计划表示如果索引seles_type列,则成本为1.