In case I have two SQL tables ,table_a and table_b, both are same , except they may contain different data, I want to insert into the table_b all the rows from table_b that does not exist in table_a already, how should the query look like ? The tables contain id1 and id2 columns only. Please tell me if my question is not clear
Insert into table_a ...
Thank you
; 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
You could use the EXCEPT
operator:
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 demo 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
You can use not exist in your query:
insert into table_a(id1,id2)
select id1,id2
from table_b
where not exists(select id1,id2 from table_a)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.