全部產品
Search
文件中心

AnalyticDB:產生列

更新時間:Feb 05, 2024

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)