跳到主要内容

数组

PostgreSQL 支持数组类型,可以在单个字段中存储同类型的多个值。数组适合标签、候选项、简单权限列表等小规模集合数据。

如果集合需要频繁关联查询、统计或单独维护,建议拆分为关联表,而不是放入数组字段。

创建数组字段

数组类型通过在基础类型后增加 [] 表示。

create table public.articles (
id bigint generated by default as identity primary key,
title text not null,
tags text[] not null default '{}',
scores int[] default '{}'
);

插入数据时可以使用数组字面量或 array[...] 语法。

insert into public.articles (title, tags, scores)
values
('PostgreSQL 入门', array['database', 'postgres'], array[90, 95]),
('CloudBase 实战', array['cloudbase', 'serverless'], array[88]);

查询数组

常见数组操作符如下:

操作符说明示例
@>左侧数组包含右侧数组tags @> array['postgres']
<@左侧数组被右侧数组包含array['postgres'] <@ tags
&&两个数组存在交集tags && array['cloudbase', 'postgres']
select id, title
from public.articles
where tags @> array['postgres'];

查询数组长度可以使用 cardinality

select id, title, cardinality(tags) as tag_count
from public.articles
where cardinality(tags) > 1;

通过 HTTP API 查询

HTTP API 基于 PostgREST 协议,可以使用兼容的过滤语法查询数组字段。

curl -X GET 'https://<envId>.api.tcloudbasegateway.com/v1/rdb/rest/articles?tags=cs.{postgres}' \
-H 'Authorization: Bearer <access_token>'

具体操作符以 查询数据 和 HTTP API 参考为准。

更新数组

追加元素可以使用 array_append,移除元素可以使用 array_remove

update public.articles
set tags = array_append(tags, 'tutorial')
where id = 1;

update public.articles
set tags = array_remove(tags, 'tutorial')
where id = 1;

如果通过前端直接更新数组字段,应在 RLS 的 WITH CHECK 中限制用户只能修改自己的记录。

索引优化

数组包含和重叠查询适合使用 GIN 索引。

create index articles_tags_gin_idx
on public.articles
using gin (tags);

索引会提升查询性能,但也会增加写入成本。只有在数组字段经常作为过滤条件时才建议创建。

与关联表的取舍

数组适合小规模、弱关系、整体更新的字段。例如文章标签、商品卖点、配置开关集合。

如果需要对集合元素做权限控制、排序、统计、外键约束或频繁单项更新,应使用关联表。例如文章与标签的多对多关系可以拆成 article_tags 表。