昨天我问了一个关于 postgress 的类似问题,以及它是否可以从 select 语句的结果形状中推断出类型。
今天我想从查询中返回一个结果集,这是我发现工作的查询:
DROP TYPE IF EXISTS topic_result_entry CASCADE;
CREATE TYPE topic_result_entry AS
(
id INTEGER,
last_post_at TIMESTAMP WITHOUT TIME ZONE,
is_sticky BOOLEAN,
is_poll BOOLEAN,
has_prefix BOOLEAN,
prefix CHARACTER VARYING,
title CHARACTER VARYING,
post_count INTEGER,
started_by INTEGER,
started_at TIMESTAMP WITHOUT TIME ZONE
);
CREATE OR REPLACE FUNCTION get_paginated_topics(
forum_id_ INTEGER, category_id_ INTEGER, page_number_ INTEGER, topics_per_page_ INTEGER)
RETURNS SETOF topic_result_entry as $$
DECLARE
zero_based_index INTEGER;
lower_offset INTEGER;
upper_offset INTEGER;
BEGIN
zero_based_index := page_number_ -1;
lower_offset := zero_based_index * topics_per_page_;
upper_offset := ( (topics_per_page_ * page_number_) + 1 );
RETURN query
select id,last_post_at, is_sticky, is_poll,
has_prefix, prefix, title,post_count,
started_by, started_at
from (
select row_number() OVER(ORDER by last_post_at desc) as rn, *
from forum_topics where category_id = category_id_ and forum_id= forum_id_
) as foo
where rn > lower_offset and rn < upper_offset;
END;
$$ LANGUAGE plpgsql;
结果集的形状可以从select的参数列表+源表的schema定义中推断出来。
Q1。9.1 中是否有一些语法糖,如果没有,这在路线图上吗?
Q2 有没有更简洁的方式来做到这一点?
无关
select id,last_post_at, is_sticky, is_poll,
has_prefix, prefix, title,post_count,
started_by, started_at
from (
select row_number() OVER(ORDER by last_post_at desc) as rn, *
from forum_topics where category_id = 72
) as foo
where rn>0 and rn<22
QUERY PLAN
Subquery Scan on foo (cost=0.00..492.20 rows=28 width=60)
Filter: ((foo.rn > 0) AND (foo.rn < 22))
-> WindowAgg (cost=0.00..409.42 rows=5519 width=156)
-> Index Scan using forum_topics_last_post_at_idx1 on forum_topics (cost=0.00..326.63 rows=5519 width=156)
Filter: (category_id = 72)