MySQL – How to Merge Tables from Two Databases

mergeMySQL

I have two MySql databases DB1 and DB2. Each of them has tables tbl1 and tbl2. These two tables have the same primary key (Column1). Tables in DB1 have N rows. I want to create new database and table, which will look like:

DB1.tbl1.Col1   | DB1.tbl1.Col2 | ... | DB1.tbl1.ColK | DB1.tbl2.Col2 | DB1.tbl2.ColZ
    ...         |    ...        | ... |     ...       |    ...        |      ...   
DB2.tbl1.Col1+N | DB2.tbl1.Col2 | ... | DB2.tbl1.ColK | DB2.tbl2.Col2 | DB2.tbl2.ColZ
    ...         |    ...        | ... |     ...       |    ...        |      ...   

But, I could not use MERGE as I need indexes in DB2.tbl1.Col1 in new table to be DB3.tbl.Col1=DB1.tbl1.Col1, DB2.tbl1.Col1+N.

I now how to do it on the side of client (on Python), but is it possible to do it via some MySql script on server side?

Thank you.

Best Answer

how about?

create table DB3.tbl1 as
select * from (
  select
    DB1.tbl1.Col1,
    DB1.tbl1.Col2, ...
    DB1.tbl1.ColZ
  from DB1.tbl1
  union all
  select
    DB2.tbl1.Col1 + n
    DB2.tbl1.Col2, ...
    DB2.tbl1.ColZ
  from DB2.tbl1
)

could also replace the + n by + ( select count(*) from DB1.tbl1 )