Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql insert rows from another table based on condition

Tags:

sql

sql-server

Consider the following two tables

Table 1

ID    DATA
1      'A'
2      'B'
3      'C'
4      'D'
5      'E'
6      'F'

Table 2

ID    DATA
2       'G'
3       'F'
4       'Q'

How do I insert data into Table 1 from Table 2 where Table 2 doesn't have Table 1's ID?

In other words, I'd like the following result:

Table 2

ID    DATA
1       'A'
2       'G'
3       'F'
4       'Q'
5       'E'
6       'F'
like image 326
l46kok Avatar asked Dec 26 '13 00:12

l46kok


1 Answers

The wording in your question a little bit confusing because you first ask How do I insert data into Table 1 from Table 2 but then you're showing the desired result for Table2.

Now if you want to insert rows from table1 into table2 with ids that doesn't exist in table2 you can do it this way

INSERT INTO Table2 (id, data)
SELECT id, data
  FROM Table1 t
 WHERE NOT EXISTS
(
  SELECT * 
    FROM Table2
   WHERE id = t.id
)

Here is SQLFiddle demo

or

INSERT INTO Table2 (id, data)
SELECT t1.id, t1.data
  FROM Table1 t1 LEFT JOIN Table2 t2
    ON t1.id = t2.id
 WHERE t2.id IS NULL;

Here is SQLFiddle demo

Outcome (in both cases):

| ID | DATA |
|----|------|
|  1 |    A |
|  2 |    G |
|  3 |    F |
|  4 |    Q |
|  5 |    E |
|  6 |    F |
like image 122
peterm Avatar answered Oct 12 '22 10:10

peterm