HighgoDB 之 临时表的使用

作者:瀚高PG实验室 (Highgo PG Lab)- 波罗
验证环境
数据库版本:HighgoDB 4.3.2 (基于PostgreSQL9.5内核)

PostgreSQL中的临时表有三个不同特性,区别于普通表:

1)临时表存储在特殊的模式( schema)中, 以便它们只对后台创建(creating backend)可见
2)临时表有本地缓冲区管理器管理,而非由共享缓冲区管理器管理
3)临时表没有预写式日志

会话级或事务级的临时表,临时表在会话结束或事物结束自动删除,任何在临时表上创建的索引也会被自动删除。

除非用模式修饰的名字引用,否则现有的同名永久表在临时表存在期间,在本会话或事务中是不可见的。

另外临时表对其他会话也是不可见的,但是会话级的临时表也可以使用临时表所在模式修饰的名字引用。

创建临时表的语法:

CREATE TEMP tbl_name()ON COMMIT{PRESERVE ROWS|DELETE ROWS|DROP};

PRESERVE ROWS:默认值,事务提交后保留临时表和数据
DELETE ROWS:事务提交后删除数据,保留临时表
DROP:事务提交后删除表

示例1
会话A:
创建临时表

highgo=#create temp table t1_temp(a int);
CREATE TABLE

会话B:
1.在会话B查询临时表t1_temp,提示表不存在

highgo=#select * from t1_temp;
ERROR:  relation "t1_temp" does not exist
LINE 1: select * from t1_temp;

2.但是在会话B查询pg_class中可以查到t1_temp的记录

highgo=# select relname,relnamespace from pg_class where relname = 't1_temp';
 relname | relnamespace 
---------+--------------
t1_temp  |       114866
(1 row)

3.从上述查询结果中可以看到临时表t_temp属于114866的模式

highgo=# select nspname from pg_namespace where oid = 114866;
  nspname  
-----------
 pg_temp_2
(1 row)

4.直接使用模式修饰的表名访问成功

highgo=# select * from pg_temp_2.t1_temp ;
 a 
---
(0 rows)

会话A:
退出会话A

会话B:
再次查询t_temp时提示不存在

highgo=# select * from pg_temp_2.t_temp ;
ERROR:  42P01: relation "pg_temp_2.t_temp" does not exist
LINE 1: select * from pg_temp_2.t_temp ;

示例2.创建ON COMMIT DELETE ROWS的临时表

highgo=#begin ;
BEGIN
highgo=#create temp table t2_temp(a int) on commit delete rows;
CREATE TABLE

highgo=#insert into t2_temp values (1);
INSERT 0 1

highgo=#select * from t2_temp ;
 a ---
 1
(1 row)

highgo=#commit ;
COMMIT

highgo=#select * from t2_temp ;
 a ---
(0 rows)

示例3.创建ON COMMIT DROP临时表

highgo=# begin;
BEGIN
highgo=# create temp table t2_temp(a int) on commit drop;
CREATE TABLE
highgo=# select * from t2_temp;
 a 
---
(0 rows)

highgo=# commit;
COMMIT

highgo=# select * from t2_temp;
ERROR:  42P01: relation "t2_temp" does not exist
LINE 1: select * from t2_temp;
                      ^

示例4.查询数据库中所有临时表

highgo=#select relname,nspname 
from pg_class join pg_namespace on(relnamespace=pg_namespace.oid) 
where pg_is_other_temp_schema(relnamespace);

 relname | relnamespace 
---------+--------------
t2_temp |       114866
(1 row)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值