0

如果我有两个 SQL 表,table_a 和 table_b,它们都是相同的,除了它们可能包含不同的数据,我想将 table_b 中 table_a 中不存在的所有行插入到 table_b 中,查询应该如何?这些表仅包含 id1 和 id2 列。如果我的问题不清楚,请告诉我

Insert into table_a ...

谢谢

4

4 回答 4

0
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
于 2013-02-26T18:02:24.947 回答
0

您可以使用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 Fiddle 演示在这里

于 2013-02-26T17:59:39.437 回答
0
; 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
于 2013-02-26T17:58:26.253 回答
0

您可以在查询中使用不存在:

insert into table_a(id1,id2)
select id1,id2 
from table_b 
where not exists(select id1,id2 from table_a)
于 2013-02-27T10:36:43.633 回答