gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:17:08 25 4
gpt4 key购买 nike

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

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

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

我尝试使用递归 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;

最佳答案

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 ;

我已经使用联合查询来实现您需要的结果。如果您的 filtered_records 返回结果,则联合后的查询将不会产生任何结果,否则联合产生结果后的查询。

关于sql - PostgreSQL:如果条件存在则选择所有具有条件的行,否则忽略条件并选择最早的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com