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

时间:2017-05-25 17:30:34

标签: sql postgresql common-table-expression

我有一个返回find_all_records_with_params()的PostgreSQL函数SETOF records。记录表包含以下列:

table records(
id integer,
type integer,
created date,
content text
);

我想选择current_date - created大于90天的所有记录。但是,如果此查询不存在,我想选择最早created日期的1条记录。

我尝试使用递归cte(如下所示)执行此操作,但它不允许使用if / else逻辑。我试图避免两次调用find_all_records_with_params()函数,如果可能的话我不想创建临时表。

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;

1 个答案:

答案 0 :(得分:3)

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 ;

我使用了union查询来实现您所需的结果。如果您的filtered_records返回结果,那么在union生成结果后,union之后的查询将不会产生任何其他结果。