簡體   English   中英

僅當第 2 個表中不存在記錄時,才將第 1 個表中的記錄插入到第 2 個表中

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

我有 1 個表與第二個表具有相同的表結構,我只需要將記錄從 table1 插入到 table2

insert into table2(select * from table1);

表 2 在其中一個字段 say(id) 中有一個主鍵,以及與該主鍵對應的某個插入數據

table1          table2

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

我必須只將那些記錄插入到表 2 中沒有填充主鍵。

插入后表 2 應如下所示


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

什么是最簡單的方法來做到這一點?

使用 NOT EXISTS 條件僅從 table1 中獲取 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);

您可以僅在 INSERT WHEN NOT MATCHED 中使用 MERGE 語句:

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)

暫無
暫無

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

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