简体   繁体   English

在2个表之间进行条件SQL插入

[英]Conditional SQL insert between 2 tables

I have table1 where I have already some nvarchar results. 我有table1,那里已经有一些nvarchar结果。

nvarchar name
name1
name3
name4

I have table2 where I have records in format 我有table2,其中我有格式的记录

nvarchar name | nvarchar subname
name1         | subname1
name1         | subname2
name1         | subname3
name1         | subname4
name2         | subname1
name2         | subname2
name3         | subname3

I need to go through all the records in table2 and group them by name, then insert all name records into table1 but with the condition they dont exist in table1 already. 我需要遍历table2中的所有记录并按名称对它们进行分组,然后将所有名称记录插入table1中,但条件是它们已不存在于table1中。

Could you please help with this? 您能帮忙吗? I would rather delete table1 and recreate it from table2 but table1 has some records which are not in table2 and they have to stay there. 我宁愿删除table1并从table2重新创建它,但是table1包含一些不在table2中的记录,它们必须留在那里。

Thank you. 谢谢。

This will insert all names from table2 into table1 that isn't already in table1: 这会将表2中的所有名称插入表1中尚未存在的表1中:

INSERT INTO table1 
(
    name
)
SELECT t2.name
FROM   table2 t2
WHERE NOT EXISTS
(
    SELECT 1
    FROM   table1 t1
    WHERE  t1.name = t2.name 
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM