私はPostgreSQL関数find_all_records_with_params()
を持っていて、SETOF records
を返します。レコードのテーブルには、次の列があります。PostgreSQL:条件付きの行をすべて選択し、条件を無視して最も古い行を選択します。
table records(
id integer,
type integer,
created date,
content text
);
私はcurrent_date - created
が90日超であるすべてのレコードを選択したいと思います。ただし、このクエリが存在しない場合は、最初にcreated
という日付のレコードを1つ選択します。
私はこれを再帰的なcte(以下に示します)を使用して実行しようとしましたが、if/elseロジックは使用できません。可能であれば、find_all_records_with_params()
関数を2回呼び出すことを避けようとしており、私は一時テーブルを作成したくありません。
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;
'current_date - created> 90' - それはかなり醜いです。どうして 'created
@DavidAldridgeは 'current_date - created'より' current_date - 90'を実行するとパフォーマンス上の利点がありますか?その値をキャッシュしていますか? –
これはオプティマイザがインデックスを使うことを可能にしますが、読むのがはるかに簡単です - 私は25年間SQLを書いてきましたが、 'current_date - created> 90'を私の目の前に置きました。それが何を意味するか。 –