So, to me comes Table2 (PK Text) filled with elements FIRST, SECOND, THIRD, FORTH. I need to insert this element to TABLE1 where these elements are missing.
TABLE1
+----+--------+ | ID | Text | +----+--------+ | A | FIRST | | A | SECOND | | A | THIRD | | B | FIRST | | B | THIRD | | C | FIRST | +----+--------+
So ID A misses FORTH
| A | FORTH |
Should be inserted
B misses SECOND and FORTH and so on
Answer should be something like that
+----+--------+ | ID | Text | +----+--------+ | A | FIRST | | A | SECOND | | A | THIRD | | A | FORTH | | B | FIRST | | B | SECOND | | B | THIRD | | B | FORTH | | C | FIRST | | C | SECOND | | C | THIRD | | C | FORTH | +----+--------+
Advertisement
Answer
You can cross join the texts from table2 with the distinct ids availabel in table1 and filter on the missing tuples with a not exists condition, like so:
insert into table1(id, text)
select t1.id, t2.text
from table2 t2
cross join (select distinct id from table1) t1
where not exists (
    select 1
    from table1 t11
    where t11.id = t1.id and t11.text = t2.text
)