Adding rows from one table to another existing table where primary key is autogenerated

StackOverflow https://stackoverflow.com/questions/21872577

  •  13-10-2022
  •  | 
  •  

Question

I have two tables say Table1(id,name) and Table2 with (id,name).

Table1 looks like:

id    name
 1     ABC
 2     DEF

Table2 looks like:

id    name
 1    XYZ
 2    ASD

Can someone shed light on how I can add Table2 rows to Table1 i.e.

Table1 must finally look like:

id  name
 1   ABC
 2   DEF
 3   XYZ
 4   ASD
Was it helpful?

Solution

Insert into table1 (name) 
Select  name from table2

OTHER TIPS

Try like below, If id in table1 is not auto_increment

SELECT * FROM table1;
+------+------+
| id   | name |
+------+------+
|    1 | ABC  |
|    2 | DEF  |
+------+------+
2 rows in set (0.00 sec)

SELECT * FROM table2;
+------+------+
| id   | name |
+------+------+
|    1 | PQR  |
|    2 | XYZ  |
+------+------+
2 rows in set (0.00 sec)

SELECT MAX(id) INTO @row FROM table1;
Query OK, 1 row affected (0.00 sec)

INSERT INTO table1 SELECT @row := @row + 1 as row, name FROM table2;
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

SELECT * FROM table1;
+------+------+
| id   | name |
+------+------+
|    1 | ABC  |
|    2 | DEF  |
|    3 | PQR  |
|    4 | XYZ  |
+------+------+
4 rows in set (0.00 sec)

To eliminate duplicities:

INSERT INTO table1 (name) 
  SELECT name 
  FROM table2 t2 
  WHERE NOT EXISTS(SELECT * FROM table1 t1 WHERE t1.name = t2.name )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top