计算字段

计算字段是虚拟列,不存储在表中。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"

重要

计算字段必须在 公开模式额外搜索路径 中的模式中创建,才能以这种方式使用。当将计算字段放在 公开模式 中时,您可以使用无名参数(如上面的示例所示)来防止它作为 RPC/rpc 下公开。

注意