postgresql----TEMPORARY TABLE和UNLOGGED TABLE

一.TEMPORARY|TEMP TABLE
会话级或事务级的临时表,临时表在会话结束或事物结束自动删除,任何在临时表上创建的索引也会被自动删除。除非用模式修饰的名字引用,否则现有的同名永久表在临时表存在期间,在本会话或事务中是不可见的。另外临时表对其他会话也是不可见的,但是会话级的临时表也可以使用临时表所在模式修饰的名字引用。

创建临时表的语法:

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

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

DELETE ROWS:事务提交后删除数据,保留临时表

DROP:事务提交后删除表

示例1

会话A:

创建临时表

test=# create temp table tbl_temp(a int);
CREATE TABLE

会话B:

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

test=# select * from tbl_temp;
ERROR: relation "tbl_temp" does not exist
LINE 1: select * from tbl_temp;
2.但是在会话B查询pg_class中可以查到tbl_temp的记录

test=# select relname,relnamespace from pg_class where relname = 'tbl_temp';

relname relnamespace
tbl_temp 16488

(1 row)
3.从上述查询结果中可以看到临时表tbl_temp属于16488的模式

test=# select nspname from pg_namespace where oid = 16488;

nspname

pg_temp_3
(1 row)
4.直接使用模式修饰的表名访问成功

test=# select * from pg_temp_3.tbl_temp ;

a

(0 rows)

会话A:

退出会话A

会话B:

再次查询tbl_temp时提示不存在

test=# select * from pg_temp_3.tbl_temp ;
ERROR: relation "pg_temp_3.tbl_temp" does not exist
LINE 1: select * from pg_temp_3.tbl_temp ;

                  ^

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

复制代码

你可能感兴趣的:(postgresql)