考虑以下两个表
表1
ID DATA 1 'A' 2 'B' 3 'C' 4 'D' 5 'E' 6 'F'
表2
ID DATA 2 'G' 3 'F' 4 'Q'
如何将表2中的数据插入表2,其中表2没有表1的ID?
换句话说,我想得到以下结果:
表2
ID DATA 1 'A' 2 'G' 3 'F' 4 'Q' 5 'E' 6 'F'
答案 0 :(得分:5)
您问题中的措辞有点令人困惑,因为您首先要求如何将数据插入 表1 2 但是您显示 Table2 所需的结果。
现在,如果你想将table1中的行插入到table2中的id
s,而table2中不存在,你可以这样做
INSERT INTO Table2 (id, data)
SELECT id, data
FROM Table1 t
WHERE NOT EXISTS
(
SELECT *
FROM Table2
WHERE id = t.id
)
这是 SQLFiddle 演示
或
INSERT INTO Table2 (id, data)
SELECT t1.id, t1.data
FROM Table1 t1 LEFT JOIN Table2 t2
ON t1.id = t2.id
WHERE t2.id IS NULL;
这是 SQLFiddle 演示
结果(两种情况):
| ID | DATA | |----|------| | 1 | A | | 2 | G | | 3 | F | | 4 | Q | | 5 | E | | 6 | F |
答案 1 :(得分:0)
INSERT INTO Table2 (ID, DATA)
SELECT a.ID, a.DATA
FROM Table1 a
JOIN (
SELECT ID FROM Table1
EXCEPT
SELECT ID FROM Table2
) b
ON b.ID = a.ID
;
这里有一些你可以在SSMS中运行的代码,它们将通过以下代码来举例说明:
PRINT 'Dropping and creating temp tables';
IF OBJECT_ID('tempdb.dbo.#t1') IS NOT NULL DROP TABLE #t1;
IF OBJECT_ID('tempdb.dbo.#t2') IS NOT NULL DROP TABLE #t2;
CREATE TABLE #t1 (
ID INT, DATA VARCHAR(1)
);
CREATE TABLE #t2 (
ID INT, DATA VARCHAR(1))
;
PRINT 'Temp tables created';
PRINT 'Inserting test data into temp tables';
INSERT INTO #t1 (
ID, DATA
)
VALUES
(1, 'A')
,(2, 'B')
,(3, 'C')
,(4, 'D')
,(5, 'E')
,(6, 'F')
;
INSERT INTO #t2 (
ID, DATA
)
VALUES
(2, 'G')
,(3, 'F')
,(4, 'Q')
;
PRINT 'Test data inserted';
PRINT 'SELECTING temp tables before modifying data'
SELECT * FROM #t1;
SELECT * FROM #t2;
PRINT 'Modifying data'
INSERT INTO #t2 (ID, DATA)
SELECT a.ID, a.DATA
FROM #t1 a
JOIN (
SELECT ID FROM #t1
EXCEPT
SELECT ID FROM #t2
) b
ON b.ID = a.ID
;
PRINT 'SELECTING "after" modifying data'
SELECT * FROM #t1
SELECT * FROM #t2
PRINT 'Cleaning up (destroying temp tables)'
IF OBJECT_ID('tempdb.dbo.#t1') IS NOT NULL DROP TABLE #t1;
IF OBJECT_ID('tempdb.dbo.#t2') IS NOT NULL DROP TABLE #t2;