Merging two tables into one with the same column names

依然范特西╮ 提交于 2020-01-06 19:50:47

问题


I use this command to merge 2 tables into one:

CREATE TABLE table1 AS 
SELECT name, sum(cnt)
FROM (SELECT * FROM table2 UNION ALL SELECT * FROM table3) X
GROUP BY name
ORDER BY 1;

table2 and table3 are tables with columns named name and cnt, but the result table (table1) has the columns name and sum.

The question is how to change the command so that the result table will have the columns name and cnt?


回答1:


In the absence of an explicit name, the output of a function inherits the basic function name in Postgres. You can use a column alias in the SELECT list to fix this - like @hennes already supplied.

If you need to inherit all original columns with name and type (and possibly more) you can also create the table with a separate command:

  • To copy columns with names and data types only, still use CREATE TABLE AS, but add LIMIT 0:

    CREATE TABLE table1 AS
    TABLE table2 LIMIT 0;  -- "TABLE" is just shorthand for "SELECT * FROM" 
    
  • To copy (per documentation):

    all column names, their data types, and their not-null constraints:

    CREATE TABLE table1 (LIKE table2);
    

    ... and optionally also defaults, constraints, indexes, comments and storage settings:

    CREATE TABLE table1 (LIKE table2 INCLUDING ALL);
    

    ... or, for instance, just defaults and constraints:

    CREATE TABLE table1 (LIKE table2 INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
    

Then INSERT:

INSERT INTO table1 (name, cnt)
SELECT ...        -- column names are ignored



回答2:


Have you tried this (note the AS cnt)?

CREATE TABLE table1 AS SELECT name,sum(cnt) AS cnt
  FROM ...


来源:https://stackoverflow.com/questions/25591824/merging-two-tables-into-one-with-the-same-column-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!