如果我有兩個SQL表,table_a和table_b,都是相同的,除了它們可能包含不同的數據,我想插入到table_b中所有來自table_b的行中不存在的行table_a已經存在,查詢應該如何?這些表只包含id1和id2列。 請告訴我,如果我的問題不明確插入表沒有相交部分
Insert into table_a ...
謝謝
如果我有兩個SQL表,table_a和table_b,都是相同的,除了它們可能包含不同的數據,我想插入到table_b中所有來自table_b的行中不存在的行table_a已經存在,查詢應該如何?這些表只包含id1和id2列。 請告訴我,如果我的問題不明確插入表沒有相交部分
Insert into table_a ...
謝謝
; with cte_left as
(
select id1+id2
from table_a
where id1+id2 not in (select id1+id2 from table_b)
)
insert into table_b
select * from cte_left
您可以使用EXCEPT
操作:
INSERT INTO table_a (id1, id2)
SELECT id1, id2
FROM (
SELECT id1, id2
FROM table_b
EXCEPT
SELECT id1, id2
FROM table_a
) except_gry
SQL小提琴演示here
Insert into table_a (id1, id2)
select b.id1, b.id2
from table_b b
left outer join table_a a on a.id1 = b.id1 and a.id2 = b.id2
where a.id1 is null
您可以在您的查詢中不存在:
insert into table_a(id1,id2)
select id1,id2
from table_b
where not exists(select id1,id2 from table_a)