web-dev-qa-db-fra.com

Comment fusionner deux tables dans postgresql?

J'ai deux tables

tableau 1:

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

tableau 2:

name |count
xxx  | 1
aaa  | 5

Je veux que le tableau résultant soit comme le tableau suivant:

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

Est-ce que quelqu'un sait comment faire ça?

18
user1897937

Vous devez utiliser UNION.

select * from table1
union
select * from table2

Pour insérer dans le tableau 1:

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

Nous n'avons besoin d'aucune commande MERGE/UPSERT spéciale.

  1. Pour fusionner des lignes d'une table dans l'autre.

    INSERT INTO table1
      (SELECT * FROM table2
       WHERE name NOT IN
           (SELECT name FROM table1));
    
  2. Pour créer une nouvelle table à partir d'anciennes tables.

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

Pouvez-vous vérifier si cela fonctionne dans votre développeur,

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