PostgreSQL:选择具有条件的所有行(如果存在),否则忽略该条件并选择最早的行

PostgreSQL:选择具有条件的所有行(如果存在),否则忽略该条件并选择最早的行,sql,postgresql,common-table-expression,Sql,Postgresql,Common Table Expression,我有一个PostgreSQL函数find_all_records_,带有返回一组记录的参数。记录表包含以下列: table records( id integer, type integer, created date, content text ); 我想选择当前创建日期大于90天的所有记录。但是,如果这个查询不存在,我想选择1条创建日期最早的记录 我尝试使用如下所示的递归cte来实现这一点,但它不允许if/else逻辑。我试图避免使用参数两次调用find_all_records_,如果可能

我有一个PostgreSQL函数find_all_records_,带有返回一组记录的参数。记录表包含以下列:

table records(
id integer,
type integer,
created date,
content text
);
我想选择当前创建日期大于90天的所有记录。但是,如果这个查询不存在,我想选择1条创建日期最早的记录

我尝试使用如下所示的递归cte来实现这一点,但它不允许if/else逻辑。我试图避免使用参数两次调用find_all_records_,如果可能的话,我不希望创建临时表

with most_records as (select * from find_all_records_with_params()),
filtered_records as (select * from most_records where current_date - created > 90)
if exists(select * from filtered_records) then
select * from filtered_records;
else
select * from most_records order by created asc limit 1;
end if;
我已经使用union query实现了您所需的结果。如果过滤后的_记录返回结果,则联合后的查询将不会生成任何结果,否则联合后的查询将生成结果


我已经使用union query实现了您所需的结果。如果过滤后的\u记录返回结果,则联合后的查询将不会生成任何结果,否则联合后的查询将生成结果。

当前\u日期-创建>90-这太难看了。为什么不创建90放在我面前,我必须认真思考这意味着什么。当前创建日期>90-这太难看了。为什么不创建90,我必须认真思考这意味着什么。谢谢!当您执行where not exists select*from filtered_records limit 1时,limit 1会做什么?在where not exists子查询limit 1中,limit用于减少执行时间。因为我们只需要检查过滤后的记录中是否有记录。谢谢!当您执行where not exists select*from filtered_records limit 1时,limit 1会做什么?在where not exists子查询limit 1中,limit用于减少执行时间。因为我们只需要检查过滤后的记录中是否有记录。
with most_records as (select * from find_all_records_with_params()),
filtered_records as (select * from most_records where current_date - created > 90)
select * from filtered_records
union 
select * from 
(select * from most_records 
where not exists (select * from filtered_records limit 1) 
order by created asc limit 1 ) a ;