简体   繁体   English

Postgres - 从选择创建表

[英]Postgres - CREATE TABLE FROM SELECT

I have two tables, one contains a large list of IDs and Info regarding those ids.我有两个表,一个包含有关这些 ID 的 ID 和信息的大列表。

I have a second table Graph which just has two columns, each column contains the aforementioned id numbers, multiple times.我有第二个表Graph ,它只有两列,每列多次包含上述 ID 号。 I want to trim the size of my Info table by selecting only those ids that appear in my graph and creating a new smaller Info table.我想通过仅选择出现在我的图表中的那些 id 并创建一个新的较小的 Info 表来trim我的Info表的大小。 Is there a simple way of doing this?有没有一种简单的方法可以做到这一点?

CREATE TABLE FROM SELECT? 

Thanks!谢谢!

It's as easy as:这很简单:

create table new_table
as 
select t1.col1, t2.col2
from some_table t1
   join t2 on t1.id = t2.some_id;

You can use any select statement for that.您可以为此使用任何选择语句。 The column names of the new table are defined by the column aliases used in th query.新表的列名由查询中使用的列别名定义。

More details in the manual: http://www.postgresql.org/docs/current/static/sql-createtableas.html手册中的更多详细信息: http : //www.postgresql.org/docs/current/static/sql-createtableas.html

You can create TEMP table if you need those small table only for that session.如果您只需要该会话的那些小表,您可以创建 TEMP 表。 you can use below query to do that.您可以使用以下查询来做到这一点。

  DROP TABLE IF EXISTS temp_table;
    CREATE TEMP TABLE temp_table AS
     SELECT 
       i.id as info_id, i.information as information
     FROM
      info i
      INNER JOIN graph g ON i.id = g.id;

Now you can use this temp_table for your next table in the function.现在您可以将此 temp_table 用于函数中的下一个表。

                    OR 

you can also create table like below (if you not want to create it as TEMP):您还可以创建如下表(如果您不想将其创建为 TEMP):

CREATE TABLE temp_table AS
     SELECT 
       i.id as info_id, i.information as information
     FROM
      info i
      INNER JOIN graph g ON i.id = g.id;

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

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