如果我有两个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)