Naguib Ihab
Naguib Ihab

Reputation: 4496

MySQL: Merging two tables together

Just wondering, if I have two tables that have some common columns (might be in different order though) and some different columns, is there an easy way to merge the two structures together so that both of them would have the same columns?

I tried exporting the structure of both and merging the files together aiming to have a create query that creates a merged table but because the common columns are not in the same order I end up trying to add the same column twice.

Or maybe if there's a query like:

ALTER TABLE `example` ADD IGNORE...

Upvotes: 0

Views: 144

Answers (3)

Naguib Ihab
Naguib Ihab

Reputation: 4496

Eventually what worked for me was exporting both tables' structures and taking their add column queries in an excel column and removing the duplicates and just creating a new query with the unique queries that were left which are the unique columns in both tables.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269803

I think you want a union all query:

select col1, col2, col3, NULL as col4, col5
from table1
union all
select col1, col2, col3, col4, NULL as col5
form table2;

Upvotes: 1

Alex
Alex

Reputation: 17289

You should look at 'JOIN' so if your_table has more records and you need some additional columns from your_second_table and tables are connected by some common_field column in both you can:

SELECT t.*, t2.*
FROM your_table t
LEFT JOIN your_second_table t2
ON t.common_field = t2.common_field
  AND t.another_common_field = t2.another_common_field

Upvotes: 0

Related Questions