sql-如果行不存在,则返回一行常量值
如果查询没有返回任何行,我希望能够返回一行sql-如果行不存在,则返回一行常量值,sql,jdbctemplate,named-parameters,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 l
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'));
从DB中,存在james
和smith
的条目,但不存在hankers
的条目
但此查询仅在条目存在时返回。不返回none,none,0
我做错了什么
编辑:在本例中,我将3个硬编码值作为
last
传递,但我想知道如果我们通过getJdbcTemplate将值作为列表参数(如so(:last)
)传递进来,有何解决方法。应用不存在
时考虑了列出的所有值。因此,如果存在任何一个值,则不满足不存在
作为一种解决方法,您可以使用具有指定值的内嵌表,并将原始表左键连接到该表:
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
。不存在的应用考虑了列出的所有值。因此,如果存在任何一个值,则不满足不存在
作为一种解决方法,您可以使用具有指定值的内嵌表,并将原始表左键连接到该表:
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
将返回。这将对您有所帮助
_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
希望这对你有帮助
_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
你可以使用rowcount,比如这里:你使用了哪一个db?好的,我支持aguetat,但是他的例子在msSql中,但是在oracle中,你可以选择count进行检查。你可以使用rowcount,比如这里:你使用了哪一个db?好的,我支持aguetat,但是他的例子在msSql中,但是在oracle中,你可以选择count进行检查。我明白了。非常感谢。然而,我应该在最初的帖子中澄清,但是如果我们不知道last
参数的确切大小,那么解决方法是什么呢?在本例中,我将硬编码的3个值作为last
传递,但在我的实际SQL中,我不知道这些值,并且在(:last)中传递一个类似于的列表参数代码>@qollers另一个解决方法是用所有值填充临时表。如果要检索姓氏信息,必须将其存储在某种关系结构中。我明白了。非常感谢。然而,我应该在最初的帖子中澄清,但是如果我们不知道last
参数的确切大小,那么解决方法是什么呢?在本例中,我将硬编码的3个值作为last
传递,但在我的实际SQL中,我不知道这些值,并且在(:last)中传递一个类似于的列表参数代码>@qollers另一个解决方法是用所有值填充临时表。如果要检索姓氏信息,必须将其存储在某种关系结构中。\u count NUMBER(10)代码>我们在这里声明数字变量吗?很抱歉,我是SQL的初学者。如果您使用存储过程执行db操作,您可以声明变量。\u count NUMBER(10)代码>我们在这里声明数字变量吗?很抱歉,我是SQL的初学者。如果您使用存储过程执行db操作,您可以声明变量。