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)