Skip to content
Advertisement

How can I merge two SQL tables and then append the result to a third?

Say I have the following three tables:

Table 1

ID NAME
 1 John

Table 2

ID   ITEM
 1  apple
 2 orange
 3 banana

Table 3

ID NAME   ITEM
 1 Mike  mango
 2 Mike  grape

What is the most efficient way using SQL to merge Tables 1 and 2 together and append the result to Table 3 in order to get the following result (but leave 1 and 2 as they are)?

Table 3 after operation

ID NAME   ITEM
  1 Mike  mango
  2 Mike  grape
  3 John  apple
  4 John orange
  5 John banana

Advertisement

Answer

Just insert a cross join between the 2.
But don’t insert those that already exist in table 3.

insert into "Table 3" (name, item) 
select t1.name, t2.item
from "Table 1" as t1
cross join "Table 2" as t2
where not exists (
  select 1
  from "Table 3" t3
  where t3.name = t1.name
    and t3.item = t2.item
);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement