生成列
更新时间:
复制为 MD 格式
AnalyticDB PostgreSQL版7.0版本支持生成列特性。您可以根据其他列的值定义一个生成列,生成列不支持通过INSERT和UPDATE直接写入数据,当写入数据到原始列时,会自动计算表达式并将结果写入生成列。
语法
GENERATED ALWAYS AS ( generation_expr ) STORED
参数介绍
| 参数 | 说明 |
| generation_expr | 需要引用的原始列。 说明
|
| STORED | 生成列的数据是需要实际存储到磁盘上的,目前暂时只支持STORED 。 |
示例
- 创建测试表t1。
CREATE TABLE t1 (stuid int4, chinese int2, math int2, sum_score int2 GENERATED ALWAYS AS (chinese+math) STORED ) distributed by (stuid); - 查看测试表t1的结构。
在psql上执行
\d t1命令查看表结构,返回如下信息:Table "public.t1" Column | Type | Collation | Nullable | Default -----------+----------+-----------+----------+--------------------------------------------- stuid | integer | | | chinese | smallint | | | math | smallint | | | sum_score | smallint | | | generated always as (chinese + math) stored Distributed by: (stuid) - 为测试表t1插入数据。
INSERT INTO t1(stuid,chinese,math) VALUES(1, 90, 95); - 查询测试表t1数据。
SELECT * FROM t1;返回如下信息:stuid | chinese | math | sum_score -------+---------+------+----------- 1 | 90 | 95 | 185 (1 row) - 向生成列直接写入数据。
INSERT INTO t1 (stuid, chinese, math, sum_score) VALUES(1,80,70,100);返回如下错误信息,说明虚拟列不支持直接写入数据。ERROR: cannot insert into column "sum_score" DETAIL: Column "sum_score" is a generated column - 在生成列上建立索引。
CREATE INDEX ON t1 USING BTREE(sum_score); - 查看测试表t1的结构。
在psql上执行
\d t1命令查看表结构,返回如下信息,说明成功为生成列建立了索引。Table "public.t1" Column | Type | Collation | Nullable | Default -----------+----------+-----------+----------+--------------------------------------------- stuid | integer | | | chinese | smallint | | | math | smallint | | | sum_score | smallint | | | generated always as (chinese + math) stored Indexes: "t1_sum_score_idx" btree (sum_score) Distributed by: (stuid)
该文章对您有帮助吗?