sql - 如果行不存在,则返回一行常量值

时间:2016-11-12 08:03:40

标签: sql jdbctemplate named-parameters

如果查询没有返回任何行,我希望能够返回none, none, 0行。我有这个SQL:

select first, last, count(address)
from employee
where last in ('james', 'smith', 'hankers')
group by first, last
union all 
select 'none', 'none', 0
from dual
where not exists (select * from employee where last in ('james', 'smith', 'hankers'));

从数据库中,jamessmith的条目存在,但hankers没有条目。

但是此查询仅在条目存在时返回。不返回none, none, 0

我在这里做错了什么?

编辑:在这个例子中,我将3个硬编码值作为last传递,但是如果我们将值作为列表参数传递给(:last),我想知道一个解决方法。通过getJdbcTemplate。

2 个答案:

答案 0 :(得分:0)

应用NOT EXISTS时会考虑所列值的所有。因此,如果存在任何一个值,则不满足NOT EXISTS

作为一种解决方法,您可以使用具有指定值的内联表,并将原始表连接到它:

select coalesce(t2.first, 'none'), 
       coalesce(t2.last, 'none'), 
       count(t2.address)
from (
   select 'james' as last
   union all
   select 'smith'
   union all
   select 'hankers') t1
left join employee t2 ON t1.last = t2.last
group by coalesce(t2.first, 'none'), 
         coalesce(t2.last, 'none')

如果不匹配,就像last='hankers'的情况一样,则count(t2.address)评估为0,从而返回'none', 'none', 0

答案 1 :(得分:0)

愿这对你有帮助,

_count NUMBER(10);

select count(*) into _count
from employee
where last in ('james', 'smith', 'hankers');

if(_count > 0)
then
   select first, last, count(address) c
   from employee
   where last in ('james', 'smith', 'hankers')
   group by first, last
else
   select 'none' first, 'none' last, 0 c   from dual
end if