【问题标题】:sql - return a row of constant values if row does not existsql - 如果行不存在,则返回一行常量值
【发布时间】:2016-11-12 08:03:40
【问题描述】:

如果查询没有返回行,我希望能够返回一行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 中,jamessmith 的条目存在,但 hankers 不存在条目。

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

我在这里做错了什么?

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

【问题讨论】:

  • 你可以使用rowcount,像这里:stackoverflow.com/questions/2884996/…
  • 你用的是哪个数据库?
  • 好吧,我支持aguetat,但是他的例子在msSql中,但是在oracle中,可以选择count进行检查。

标签: sql jdbctemplate named-parameters


【解决方案1】:

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

【讨论】:

  • 我明白了。谢谢你。但是,我应该在原始帖子中澄清,但是如果我们不知道 last 参数的确切大小,解决方法是什么?在示例中,我将硬编码的 3 个值作为last 传递,但在我的实际 SQL 中,我不知道这些值并传递了一个像这样的列表参数 in (:last);
  • @qollers 另一种解决方法是使用所有值填充临时表。如果要检索姓氏信息,必须将其存储在某种关系结构中。
【解决方案2】:

希望对你有帮助,

_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); 我们在这里声明数字变量吗?抱歉,我是 SQL 初学者
  • 如果使用存储过程进行db操作,可以声明变量。
猜你喜欢
  • 2019-11-12
  • 2019-02-15
  • 2020-04-17
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多