从选择中创建临时表,或者如果表已经存在则插入 [英] Create a temporary table from a selection or insert if table already exist

查看:197
本文介绍了从选择中创建临时表,或者如果表已经存在则插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建临时表(如果尚不存在)并将所选行添加到其中的最佳方法是什么?

What is the best way to create a temporary table, if it does not already exist, and add the selected rows to it?

推荐答案

创建表AS



是最简单,最快的方法:

CREATE TABLE AS

is the simplest and fastest way:

CREATE TEMP TABLE tbl AS
SELECT * FROM tbl WHERE ... ;



不确定表是否已经存在



如果不存在则创建表... 是在Postgres 9.1版本中引入的。

对于旧版本,请使用以下相关答案中提供的功能:

< a href = https://stackoverflow.com/questions/1766046/postgresql-create-table-if-not-exists/7438222#7438222> PostgreSQL创建表(如果不存在)

Not sure whether table already exists

CREATE TABLE IF NOT EXISTS ... was introduced in version Postgres 9.1.
For older versions, use the function provided in this related answer:
PostgreSQL create table if not exists

然后:

INSERT INTO tbl (col1, col2, ...)
SELECT col1, col2, ...

机会是,如果临时文件在代码中出了问题表已经存在。确保您没有重复表格中的数据或其他内容。或考虑以下段落...

Chances are, something is going wrong in your code if the temp table already exists. Make sure you don't duplicate data in the table or something. Or consider the following paragraph ...

临时表仅在当前会话中可见(不要与交易混淆!)。因此,表名不能与其他会话冲突。

如果在会话中需要唯一的名称,则可以使用动态SQL并使用 SEQUENCE

Temporary tables are only visible within your current session (don't confuse with transaction!). So the table name cannot conflict with other sessions.
If you need unique names within your session, you could use dynamic SQL and utilize a SEQUENCE:

创建一次:

CREATE SEQUENCE tablename_helper_seq;

您可以使用 DO 语句(或一个plpgsql函数):

You could use a DO statement (or a plpgsql function):

DO
$do$
BEGIN

EXECUTE
'CREATE TEMP TABLE tbl' || nextval('tablename_helper_seq'::regclass) || ' AS
SELECT * FROM tbl WHERE ... ';

RAISE NOTICE 'Temporary table created: "tbl%"' || ', lastval();
END
$do$;

lastval() currval(regclass) 在这种情况下有助于获得实际使用的名称。

lastval() and currval(regclass) are instrumental in this case to get the name actually used.

这篇关于从选择中创建临时表,或者如果表已经存在则插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆