[英]Get case result field when select don't have rows
讓我們更好地解釋一下:
僅當某些條件為真時,才需要更新表。
當條件為真時,將進行更新,並且我將獲取更新的字段以及使用返回鍵更新的行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次之后,結果對於“ liberou”字段為“ NOT”,而其他字段可以為null ...
我怎樣才能做到這一點???
select true as liberou, liberado.*
from liberado
union all
select false, null, null, null
order by liberou desc
limit 1
如果在true
之前返回false
命令,那么如果返回行A,則將返回“ true”行,否則將返回false
行。
此查詢:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.