简体   繁体   中英

Insert records from 1st table to 2nd table only when the record is not present in the 2nd table

I have 1 table with the same table structure as the second table, I just have to insert records from table1 to table2 with

insert into table2(select * from table1);

The table 2 has a primary key in one of the fields say(id), and some one inserted data corresponding to that primary key

table1          table2

id | name      id | name
 1 | new1       1 | old1
 2 | new2       4 | new4
 3 | new3       3 | old3
 5 | new5       6 | old6

I have to insert only those records into table 2 for which the primary key is not populated.

After insertion table 2 should look like this


table 2
id | name
1  | old1
2  | new2
3  | old3
4  | new4
5  | new5
6  | old6

What is the easiest way to do this?

Use a NOT EXISTS condition to get only those rows from table1 that don't exists in table2:

insert into table2 (id, name)
select t1.id, t1.name
from table1 t1
where not exists (select *
                  from table2 t2
                  where t2.id = t1.id);

You could use MERGE statement with only INSERT WHEN NOT MATCHED:

MERGE INTO table2 t2
USING table1 t1
  ON t1.id = t2.id
WHEN NOT MATCHED
THEN 
   INSERT INTO table2
     (id, name)
   VALUES
      (t1.id, t1.name)

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