简体   繁体   中英

Postgres - CREATE TABLE FROM SELECT

I have two tables, one contains a large list of IDs and Info regarding those ids.

I have a second table Graph which just has two columns, each column contains the aforementioned id numbers, multiple times. 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. 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

You can create TEMP table if you need those small table only for that session. 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.

                    OR 

you can also create table like below (if you not want to create it as 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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