数组
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 中限制用户只能修改自己的记录。