我有以下两个表:
table 1 table 2
+-------------+------+ +-------------+------+
| ssn | id | | ssn | id |
+-------------+------+ +-------------+------+
| 123456789 | 123 | | 123456789 | k12 |
| 123456789 | 456 | | 999999999 | k11 |
| 123456789 | 789 | +-------------+------+
| 123456789 | k12 |
| 999999999 | 799 |
+-------------+------+
如果没有匹配的id,我想要做的是将表2中的数据与表1中的数据合并。所以应该忽略123456789,因为该成员已经显示了id为k12。记录999999999 k11应添加到表1中。
答案 0 :(得分:2)
有几种方法可以做到这一点。这是使用NOT EXISTS
:
INSERT INTO Table1
SELECT T2.ssn, T2.id
FROM Table2 T2
WHERE NOT EXISTS (
SELECT 1
FROM Table1 T1
WHERE T1.id = T2.id)
或者您可以使用NOT IN
:
INSERT INTO Table1
SELECT ssn, id
FROM Table2
WHERE id NOT IN (SELECT id FROM Table1)
答案 1 :(得分:0)
INSERT INTO @Table1
( ssn, id)
SELECT t2.ssn, t2.id
FROM @table2 as t2
LEFT JOIN @table1 as t1
ON t1.id = t2.id or t1.ssn = t2.ssn
WHERE t1.id IS NULL;
如果您担心id或ssn中的重复项,只会在两者都是唯一时插入
答案 2 :(得分:0)
如果您需要经常在大型表上执行此操作,则此LEFT JOIN方法可能会执行得更快。
INSERT INTO Table1
SELECT T2.ssn, T2.id
FROM Table2 T2
LEFT JOIN Table1 t1 ON t1.id = t2.id
WHERE t1.id IS NULL