怎么使用PostgreSQL 12中的generated columns
这篇文章主要介绍“怎么使用PostgreSQL 12中的generated columns”,在日常操作中,相信很多人在怎么使用PostgreSQL 12中的generated columns问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么使用PostgreSQL 12中的generated columns”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
在其他数据库中,generated columns又被成为计算列(calculated columns)/虚拟列(virtual columns)等.
简介
在PG 11或以前的版本中,generated columns是不支持的:
testdb=#droptableifexistst_generated_col;NOTICE:table"t_generated_col"doesnotexist,skippingDROPTABLEtestdb=#createtablet_generated_coltestdb-#(n1int,testdb(#n2int,testdb(#c1varchar(10),testdb(#c2varchar(10),testdb(#counterintgeneratedalwaysas(n1+n2)stored,testdb(#linkvarchar(20)generatedalwaysas(c1||c2)stored);ERROR:syntaxerroratornear"("LINE6:counterintgeneratedalwaysas(n1+n2)stored,^
counter列的值由n1和n2相加而得,而link列的值有c1和c2拼接而得.
在PG 12中,可以支持generated columns
testdb=#droptableifexistst_generated_col;psql:NOTICE:table"t_generated_col"doesnotexist,skippingDROPTABLEtestdb=#createtablet_generated_coltestdb-#(n1int,testdb(#n2int,testdb(#c1varchar(10),testdb(#c2varchar(10),testdb(#counterintgeneratedalwaysas(n1+n2)stored,testdb(#linkvarchar(20)generatedalwaysas(c1||c2)stored);CREATETABLEtestdb=#insertintot_generated_col(n1,n2,c1,c2)values(1,1,'c1','c2');INSERT01testdb=#testdb=#select*fromt_generated_col;n1|n2|c1|c2|counter|link----+----+----+----+---------+------1|1|c1|c2|2|c1c2(1row)
生成列的值由表达式的值计算而得,如为null则为null:
testdb=#insertintot_generated_col(n1,n2,c1,c2)values(1,null,'c1',null);INSERT01testdb=#select*fromt_generated_col;n1|n2|c1|c2|counter|link----+----+----+----+---------+------1|1|c1|c2|2|c1c21||c1|||(2rows)
生成列不能被update:
testdb=#updatet_generated_colsetcounter=10;psql:ERROR:column"counter"canonlybeupdatedtoDEFAULTDETAIL:Column"counter"isageneratedcolumn.
可以创建在其上创建index:
testdb=#createindexidx_t_generated_col_counteront_generated_col(counter);CREATEINDEX
执行查询时,跟普通列没有什么区别:
^testdb=#insertintot_generated_col(n1,n2)selectx,0fromgenerate_series(1,10000)x;INSERT010000testdb=#testdb=#explainselect*fromt_generated_colwherecounter=1000;QUERYPLAN----------------------------------------------------------------------------------------------------IndexScanusingidx_t_generated_col_counteront_generated_col(cost=0.29..8.30rows=1width=23)IndexCond:(counter=1000)(2rows)
到此,关于“怎么使用PostgreSQL 12中的generated columns”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。