SQL 如何在 postgresql 中合并两个表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14065408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:50:55  来源:igfitidea点击:

How do I merge two tables in postgresql?

sqlpostgresql-9.1

提问by user1897937

I have two tables

我有两张桌子

table 1:

表格1:

name| count
xxx  | 1
yyyy | 2
zzzz | 3

table 2:

表2:

name |count
xxx  | 1
aaa  | 5

I want the resulting table to be like the following table:

我希望结果表如下表所示:

name | count
xxx  | 1
yyyy | 2
zzzz | 3
aaa  | 5

Does anyone know how to do this?

有谁知道如何做到这一点?

回答by valex

You should use UNION.

你应该使用联合。

select * from table1
union
select * from table2

To insert into table 1:

要插入表 1:

INSERT INTO TABLE1
select * from table2 
    where not exists(
            select * from table1 
                 where name=TABLE2.Name 
                       and count=TABLE2.Count
                     )

回答by Sandeep

We don't need any special MERGE/UPSERT Command.

我们不需要任何特殊的 MERGE/UPSERT 命令。

  1. To merge rows from one table into the other.

    INSERT INTO table1
      (SELECT * FROM table2
       WHERE name NOT IN
           (SELECT name FROM table1));
    
  2. For creating new table from old tables.

    CREATE TABLE new_table AS
    (SELECT * FROM table1
    UNION
    SELECT * FROM table2);
    
  1. 将一个表中的行合并到另一个表中。

    INSERT INTO table1
      (SELECT * FROM table2
       WHERE name NOT IN
           (SELECT name FROM table1));
    
  2. 用于从旧表创建新表。

    CREATE TABLE new_table AS
    (SELECT * FROM table1
    UNION
    SELECT * FROM table2);
    

回答by Mari

Can you check whether this is working in your developer,

你能检查一下这是否在你的开发人员中工作,

MERGE INTO table1 x
USING table2 b
ON ( x.name=b.name and x.count=b.count)
WHEN NOT MATCHED THEN
INSERT (x.name,x.count)VALUES(b.name,b.count);