Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two mysql tables into a third table

Tags:

merge

mysql

I have two mysql tables:

table 1:

    id  name  type
     1    a    123
     2    b    125

table 2:

    id  text
    1   test1
    2   test2

these two tables need to be merged into a third table

table3:

    id name type text

The id is an auto increment id. the first two tables have data that are not related. I mean, row for id=1 in table 1 has nothing to do with the row for id=1 in table two. So, I basically want to write a sql script which would insert values into table 3 to look like this in the end:

table3:

    id name  type   text
    1   a    123
    2   b    125
    3               test1
    4               test2

the ids in the old tables and the new table don't have to match. Just the data from the tables need to be in the new table. I am very new to mysql and if anyone can help me with this, it would be great!

thanks!

like image 538
ridermule Avatar asked Jan 30 '26 07:01

ridermule


2 Answers

It can be done with something like this:

CREATE TABLE Table3 (
  id int auto_increment, 
  name ..., 
  type int, 
  text ...,
  PRIMARY KEY (id)
);

INSERT INTO table3 (name, type, text) 
     SELECT name, type, text FROM (
       SELECT name, type, NULL AS text FROM table1
       UNION ALL
       SELECT NULL as name, NULL as type, text FROM table2) AS t

With auto-increment, we don't need to recount id at all.

Here's an SQL Fiddle for you to play with. )

I actually didn't understand what empty space in your scheme was for, and assumed it's all NULLs. If not, you can just replace NULL in this query with whatever default values you'd like.

like image 191
raina77ow Avatar answered Feb 01 '26 22:02

raina77ow


Since nothing's related, start with @raina77ow's table, but just use two queries:

INSERT INTO table3 (name, type, text)
SELECT name, type, NULL
from table1;

INSERT INTO table3 (name, type, text)
SELECT NULL, NULL, text
from table2;
like image 35
Alain Collins Avatar answered Feb 01 '26 23:02

Alain Collins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!