简体   繁体   English

在 SQL 中创建临时表

[英]Creating temporary tables in SQL

I am trying to create a temporary table that selects only the data for a certain register_type .我正在尝试创建一个临时表,该表仅选择某个register_type的数据。 I wrote this query but it does not work:我写了这个查询,但它不起作用:

$ CREATE TABLE temp1
(Select 
    egauge.dataid,
    egauge.register_type,
    egauge.timestamp_localtime,
    egauge.read_value_avg
from rawdata.egauge
where register_type like '%gen%'
order by dataid, timestamp_localtime ) $

I am using PostgreSQL.我正在使用 PostgreSQL。
Could you please tell me what is wrong with the query?你能告诉我查询有什么问题吗?

You probably want CREATE TABLE AS - also works for TEMPORARY ( TEMP ) tables:您可能想要CREATE TABLE AS - 也适用于TEMPORARY ( TEMP ) 表:

CREATE TEMP TABLE temp1 AS
SELECT dataid
     , register_type
     , timestamp_localtime
     , read_value_avg
FROM   rawdata.egauge
WHERE  register_type LIKE '%gen%'
ORDER  BY dataid, timestamp_localtime;

This creates a temporary table and copies data into it.这将创建一个临时表并将数据复制到其中。 A static snapshot of the data, mind you.请注意,数据的静态快照 It's just like a regular table, but resides in RAM if temp_buffers is set high enough.它就像一个普通的表,但如果temp_buffers设置得足够高, temp_buffers驻留在 RAM 中。 It is only visible within the current session and dies at the end of it.它仅在当前会话中可见,并在结束时消失。 When created with ON COMMIT DROP it dies at the end of the transaction .当使用ON COMMIT DROP创建时,它在事务结束时死亡。

Temp tables come first in the default schema search path , hiding other visible tables of the same name unless schema-qualified:临时表首先出现在默认模式搜索路径中,除非模式限定,否则隐藏同名的其他可见表:


If you want dynamic , you would be looking for CREATE VIEW - a completely different story.如果你想要dynamic ,你会寻找CREATE VIEW - 一个完全不同的故事。


The SQL standard also defines, and Postgres also supports: SELECT INTO . SQL 标准也定义了,Postgres 也支持: SELECT INTO But its use is discouraged : 但不鼓励使用它

It is best to use CREATE TABLE AS for this purpose in new code.最好在新代码中为此目的使用CREATE TABLE AS

There is really no need for a second syntax variant, and SELECT INTO is used for assignment in plpgsql , where the SQL syntax is consequently not possible.确实不需要第二个语法变体,并且SELECT INTO用于plpgsql中的赋值,因此 SQL 语法是不可能的。

Related:有关的:


CREATE TABLE LIKE (...) only copies the structure from another table and no data:CREATE TABLE LIKE (...)只从另一个表复制结构,没有数据:

The LIKE clause specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints. LIKE子句指定一个表,新表从该表自动复制所有列名、它们的数据类型和它们的非空约束。


If you need a "temporary" table just for the purpose of a single query (and then discard it) a "derived table" in a CTE or a subquery comes with considerably less overhead:如果您需要一个“临时”表仅用于单个查询(然后丢弃它),那么 CTE 或子查询中的“派生表”的开销要小得多:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM