怎么使用PostgreSQL 12中的generated columns

62次阅读
没有评论

共计 2538 个字符,预计需要花费 7 分钟才能阅读完成。

这篇文章主要介绍“怎么使用 PostgreSQL 12 中的 generated columns”,在日常操作中,相信很多人在怎么使用 PostgreSQL 12 中的 generated columns 问题上存在疑惑,丸趣 TV 小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么使用 PostgreSQL 12 中的 generated columns”的疑惑有所帮助!接下来,请跟着丸趣 TV 小编一起来学习吧!

在其他数据库中,generated columns 又被成为计算列 (calculated columns)/ 虚拟列(virtual columns) 等.

简介
在 PG 11 或以前的版本中,generated columns 是不支持的:

testdb=# drop table if exists t_generated_col;
NOTICE: table  t_generated_col  does not exist, skipping
DROP TABLE
testdb=# create table t_generated_col
testdb-# (n1 int,
testdb(# n2 int,
testdb(# c1 varchar(10),
testdb(# c2 varchar(10),
testdb(# counter int generated always as (n1 + n2) stored,
testdb(# link varchar(20) generated always as (c1 || c2) stored);
ERROR: syntax error at or near  (LINE 6: counter int generated always as (n1 + n2) stored,
 ^

counter 列的值由 n1 和 n2 相加而得, 而 link 列的值有 c1 和 c2 拼接而得.
在 PG 12 中, 可以支持 generated columns

testdb=# drop table if exists t_generated_col;
psql: NOTICE: table  t_generated_col  does not exist, skipping
DROP TABLE
testdb=# create table t_generated_col
testdb-# (n1 int,
testdb(# n2 int,
testdb(# c1 varchar(10),
testdb(# c2 varchar(10),
testdb(# counter int generated always as (n1 + n2) stored,
testdb(# link varchar(20) generated always as (c1 || c2) stored);
CREATE TABLE
testdb=# insert into t_generated_col(n1,n2,c1,c2) values(1,1, c1 , c2 
INSERT 0 1
testdb=# 
testdb=# select * from t_generated_col;
 n1 | n2 | c1 | c2 | counter | link 
----+----+----+----+---------+------
 1 | 1 | c1 | c2 | 2 | c1c2
(1 row)

生成列的值由表达式的值计算而得, 如为 null 则为 null:

testdb=# insert into t_generated_col(n1,n2,c1,c2) values(1,null, c1 ,null);
INSERT 0 1
testdb=# select * from t_generated_col;
 n1 | n2 | c1 | c2 | counter | link 
----+----+----+----+---------+------
 1 | 1 | c1 | c2 | 2 | c1c2
 1 | | c1 | | | 
(2 rows)

生成列不能被 update:

testdb=# update t_generated_col set counter = 10;
psql: ERROR: column  counter  can only be updated to DEFAULT
DETAIL: Column  counter  is a generated column.

可以创建在其上创建 index:

testdb=# create index idx_t_generated_col_counter on t_generated_col(counter);
CREATE INDEX

执行查询时, 跟普通列没有什么区别:

 ^
testdb=# insert into t_generated_col(n1,n2) select x,0 from generate_series(1,10000) x;
INSERT 0 10000
testdb=# 
testdb=# explain select * from t_generated_col where counter = 1000;
 QUERY PLAN 
----------------------------------------------------------------------------------------------------
 Index Scan using idx_t_generated_col_counter on t_generated_col (cost=0.29..8.30 rows=1 width=23)
 Index Cond: (counter = 1000)
(2 rows)

到此,关于“怎么使用 PostgreSQL 12 中的 generated columns”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注丸趣 TV 网站,丸趣 TV 小编会继续努力为大家带来更多实用的文章!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-24发表,共计2538字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)