Postgresql 如何利用Postgres函数中的if条件比较两个表值 创建或替换函数跟踪。获取\u最新\u异常\u自定义\u消息(id varchar) 返回varchar 语言plpgsql 作为$$ 声明 msg varchar; 开始 执行t1.message,t1.created_time,从表_1 t1开始,其中t1.id=由t1.created_time desc limit 1确定的id顺序; 执行t2.message,t2.created_time from table_2 t2,其中t2.id=id order by t2.created_time desc limit 1; 如果日期(t1.created\u time)>=日期(t2.created\u time),则msg=t1.message; 如果日期(t1.created_time)=t2\u已创建,则 msg:=t1_msg; elsif t1_创建
当我调用此函数时,它会给出错误:缺少表“t_1”的子句条目,您需要将两个查询中的一个选择为变量,以便能够在IF语句中使用它们 您的Postgresql 如何利用Postgres函数中的if条件比较两个表值 创建或替换函数跟踪。获取\u最新\u异常\u自定义\u消息(id varchar) 返回varchar 语言plpgsql 作为$$ 声明 msg varchar; 开始 执行t1.message,t1.created_time,从表_1 t1开始,其中t1.id=由t1.created_time desc limit 1确定的id顺序; 执行t2.message,t2.created_time from table_2 t2,其中t2.id=id order by t2.created_time desc limit 1; 如果日期(t1.created\u time)>=日期(t2.created\u time),则msg=t1.message; 如果日期(t1.created_time)=t2\u已创建,则 msg:=t1_msg; elsif t1_创建,postgresql,Postgresql,当我调用此函数时,它会给出错误:缺少表“t_1”的子句条目,您需要将两个查询中的一个选择为变量,以便能够在IF语句中使用它们 您的IF语句也有点混乱,因为所有三个部分都为msg指定了相同的值。我假设您至少在一种情况下要使用t2.message create or replace function trace.get_latest_exception_custom_msg(id varchar) returns varchar language plpgsql as $$ declare m
IF
语句也有点混乱,因为所有三个部分都为msg
指定了相同的值。我假设您至少在一种情况下要使用t2.message
create or replace function trace.get_latest_exception_custom_msg(id varchar)
returns varchar
language plpgsql
as $$
declare
msg varchar ;
begin
perform t1.message, t1.created_time from table_1 t1 where t1.id = id order by t1.created_time desc limit 1;
perform t2.message, t2.created_time from table_2 t2 where t2.id = id order by t2.created_time desc limit 1;
if date(t1.created_time ) >= date(t2.created_time) then msg= t1.message;
elsif d date(t1.created_time ) < date(t2.created_time) then msg= t1.message;
else msg =t1.message;
end if;
return msg;
end;
创建或替换函数跟踪。获取\u最新\u异常\u自定义\u消息(p\u id varchar)
返回varchar
语言plpgsql
作为
$$
声明
t1_msg varchar;
t1_创建日期;
t2_msg varchar;
t2_创建日期;
msg varchar;
开始
选择t1.message,t1.created\u time::date
在t1_消息中,创建t1_
来自表1 t1
其中t1.id=p_id
按t1.U创建的订单时间描述
限值1;
选择t2.message,t2.created\u time::date
在t2_消息中,t2_创建
来自表2 t2
其中t2.id=p_id
按t2排序。创建时间描述
限值1;
如果t1\u已创建>=t2\u已创建,则
msg:=t1_msg;
elsif t1_创建 msg:=t2_msg;--谢谢。如果您需要比较datetime值,那么它将是什么类型,例如:used.t2.created_time既有日期又有时间,那么您需要使用timestamp
create or replace function trace.get_latest_exception_custom_msg(p_id varchar)
returns varchar
language plpgsql
as
$$
declare
t1_msg varchar;
t1_created date;
t2_msg varchar;
t2_created date;
msg varchar;
begin
select t1.message, t1.created_time::date
into t1_msg, t1_created
from table_1 t1
where t1.id = p_id
order by t1.created_time desc
limit 1;
select t2.message, t2.created_time::date
into t2_msg, t2_created
from table_2 t2
where t2.id = p_id
order by t2.created_time desc
limit 1;
if t1_created >= t2_created then
msg := t1_msg;
elsif t1_created < t2_created then
msg := t2_msg; --<< ???
else
-- this can only happen if one (or both) of the DATEs is NULL.
msg := t1_msg;
end if;
return msg;
end;
$$