I want to be able to return a row of none, none, 0
if no row is returned from query. I have this 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'));
From DB, an entry for james
and smith
exists but no entry exists for hankers
.
But this query only returns for when an entry exists. Does not return none, none, 0
.
What am I doing wrong here?
EDIT: In this example, I am passing 3 hard coded values as last
, but I would like to know a work-around if we were passing the values in as a list parameter like so (:last)
through getJdbcTemplate.
The NOT EXISTS
is applied taking into consideration all of the values listed. So, if any one value exists then the NOT EXISTS
is not satisfied.
As a work-around you can use an in-line table with the specified values and left join your original table to it:
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')
If there is no match, as is the case for last='hankers'
, then count(t2.address)
evaluates to 0
and thus 'none', 'none', 0
is returned.
May this will help you,
_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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.