AnalyticDB PostgreSQL版7.0版本支持生成列特性。您可以根据其他列的值定义一个生成列,生成列不支持通过INSERTUPDATE直接写入数据,当写入数据到原始列时,会自动计算表达式并将结果写入生成列。

语法

GENERATED ALWAYS AS ( generation_expr ) STORED

参数介绍

参数 说明
generation_expr 需要引用的原始列。
说明
  • 只能使用不可变类型的函数和操作符。
  • 引用的列必须为本表的非生成列,不能引用其他表的非生成列。
STORED 生成列的数据是需要实际存储到磁盘上的,目前暂时只支持STORED

示例

  1. 创建测试表t1。
    CREATE TABLE t1 (stuid int4, chinese int2, math int2, sum_score int2 GENERATED ALWAYS AS (chinese+math) STORED ) distributed by (stuid);
  2. 查看测试表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)
  3. 为测试表t1插入数据。
    INSERT INTO t1(stuid,chinese,math) VALUES(1, 90, 95);
  4. 查询测试表t1数据。
    SELECT * FROM t1;
    返回如下信息:
    stuid | chinese | math | sum_score
    -------+---------+------+-----------
         1 |      90 |   95 |       185
    (1 row)
  5. 向生成列直接写入数据。
    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
  6. 在生成列上建立索引。
    CREATE INDEX ON t1 USING BTREE(sum_score);                              
  7. 查看测试表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)