选择没有行时获取案例结果字段

时间:2015-02-27 17:20:30

标签: sql postgresql sql-update sql-returning

让我们更好地解释一下:

只有在某些条件成立时我才需要更新表。

如果条件为真,则更新发生,我返回更新的字段,并使用返回键更新行的ID。

问题是当条件不满足时,更新不会发生且我的结果集为空......

您可以通过以下脚本进行模拟:

create table wn_liberacao (

  id serial not null primary key,
  data_inicial date,   
  data_final date,
  consulta_limite integer not null,   
  consulta_utilizada integer not null

);

insert into 
  wn_liberacao ( data_inicial, data_final, consulta_limite, consulta_utilizada )
        values ( '2015-01-01', '2020-12-31', 10, 0 );

所以,当你运行这个查询时:

with liberado as (

update wn_liberacao
   set consulta_utilizada = 1 + consulta_utilizada
  from ( select id from wn_liberacao where ( data_inicial <= current_date ) and ( data_final >= current_date ) and ( consulta_limite > consulta_utilizada )
--         and 1=2 
       ) liberacao
 where liberacao.id = wn_liberacao.id

returning wn_liberacao.id id_liberacao, wn_liberacao.consulta_limite, wn_liberacao.consulta_utilizada

) 

select 
  case liberado.id_liberacao
    when null then 'NOT' --0
    else 'YES' --1
  end liberou, liberado.*
  from liberado

这个查询运行的第一次10次,我收到YES ....但是第11次,结果是nulll,没有数据行......

我需要在第11次之后,结果是&#39; NOT&#39;对于&#39; liberou&#39;字段,其他字段可以为null ...

我该怎么办?

2 个答案:

答案 0 :(得分:1)

select true as liberou, liberado.*
from liberado
union all
select false, null, null, null

order by liberou desc
limit 1
false之前

true订单,因此如果有A返回行,则会返回'true'行,否则将返回false行。

答案 1 :(得分:0)

此查询:

with liberado as (

update wn_liberacao wn
   set consulta_utilizada = 1 + consulta_utilizada
  from ( select id from wn_liberacao where ( data_inicial <= current_date ) and ( data_final >= current_date ) and ( consulta_limite > consulta_utilizada )
--         and 1=2 
       ) liberacao
 where liberacao.id = wn.id

returning wn.id id_liberacao, wn.consulta_limite, wn.consulta_utilizada

) 

select 1 as liberou, liberado.*
from liberado
union all
select 0, null, null, null

order by liberou desc
limit 1

解决了我的问题...感谢Clodoaldo Neto