2

If I have Table1 as

A           B         C
1           b.1       c.1
2           b.2       c.2
1           b.3       c.3

My second table Table2 as

A          D         E        F         G
1          d.1       e.1      f.1       g.1
2          d.2       e.2      f.2       g.2

I need to insert into an empty Table3 the values from above such that it looks like this.

A            B          C            D            E
1            b.1        c.1          d.1          e.1
2            b.2        c.2          d.2          e.2
1            b.3        c.3          d.1          e.1

So basically I need to insert each row of Table1 into Table3. For each row I need to check for column A and find the corresponding value D and E from the column and insert into Table3. Is it possible to do this in one single query?

To copy Table1 to Table3 I can use the query

INSERT INTO Table3(A,B,C) SELECT A,B,C FROM Table1

And then I need to take each row from Table3 and using A update the values of D and E from Table2. Is there a better solution that I can use to insert directly from both tables to Table3? Any help is appreciated, as I am a beginner with database and queries.

2 Answers 2

3

To merge two tables, use a join:

-- INSERT ...
SELECT A, B, C, D, E
FROM Table1
JOIN Table2 USING (A);

This will not generate a result row if no matching Table2 row is found. If you want a result row in this case (with NULLs for the missing values), use an outer join instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply. I think I should have added another condition. The Table2 has other columns F G H which I do not need in Table 3. Will JOIN still work?
Comments are not intended to ask new questions; use the "Ask Question" button for that. But you might just try it out instead …
0
INSERT INTO Table3 (A,B,C,D,E) 
SELECT t1.A, t1.B, t1.C, t2.D, t2.E FROM Table1 t1
INNER JOIN Table2 t2 ON t2.A = t1.A

This might solve your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.