簡體   English   中英

如何在 postgresql 中合並兩個表?

[英]How do I merge two tables in postgresql?

我有兩張桌子

表格1:

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

表2:

name |count
xxx  | 1
aaa  | 5

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

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

有誰知道如何做到這一點?

你應該使用聯合。

select * from table1
union
select * from table2

要插入表 1:

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

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

  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);

你能檢查一下這是否在你的開發人員中工作,

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);

合並表和“更新插入”是一項常見的數據庫任務,值得在 2021 年更新此答案。假設表相同,這是 postgresql 中最簡單和最快的方法:

INSERT INTO table1
    SELECT * FROM table2
    ON CONFLICT DO NOTHING;

在填充 upsert 值之前,創建 'table2' 作為 'table1' 的空副本以確保所有列都相同:

CREATE TABLE "table2"
    AS TABLE "table1"
    WITH NO DATA;

普雷斯托。

INSERT ... ON CONFLICT DO NOTHINGUNION快得多。 至少看看explain語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM