计算字段#
计算字段是不存储在表中的虚拟列。PostgreSQL使使用表类型上的函数来实现它们成为可能。
CREATE TABLE people (
first_name text
, last_name text
, job text
);
-- a computed field that combines data from two columns
CREATE FUNCTION full_name(people)
RETURNS text AS $$
SELECT $1.first_name || ' ' || $1.last_name;
$$ LANGUAGE SQL;
对计算字段进行水平过滤#
水平滤波 可应用于计算字段。例如,我们可以做一个 全文搜索 在……上面 full_name
:
-- (optional) you can add an index on the computed field to speed up the query
CREATE INDEX people_full_name_idx ON people
USING GIN (to_tsvector('english', full_name(people)));
curl "http://localhost:3000/people?full_name=fts.Beckett"
[
{"first_name": "Samuel", "last_name": "Beckett", "job": "novelist"}
]
对计算字段进行垂直过滤#
默认情况下,计算字段不会显示在响应上,但您可以使用 垂直过滤 要包括它们,请执行以下操作:
curl "http://localhost:3000/people?select=full_name,job"
[
{"full_name": "Samuel Beckett", "job": "novelist"}
]
计算字段的排序#
有序化 在计算字段上也可以:
curl "http://localhost:3000/people?order=full_name.desc"
重要
计算字段必须在 exposed schema 中的架构中的 extra search path 以这种方式使用。将计算字段放置在 exposed schema 您可以使用 unnamed 参数,以防止它被公开为 RPC 在……下面 /rpc
。
备注
推出了PostgreSQL 12 generated columns ,它还可以基于其他列计算值。然而,它们是存储的,而不是虚拟的。
“计算字段”记录在https://www.postgresql.org/docs/current/rowtypes.html#ROWTYPES-USAGE上(搜索“计算字段”)
在以前的PostgREST版本中,此功能的文档名称为“Computed Columns”。