Is there a way to merge two databases, same schema, with a lot of foreign key costraints and incremental id into one single database? DATABASE A
users
id name profile_id
1  jhon          1
2  smith         2

profile_id:
id email user_id
 1 a@g.c       1
 2 c@g.c       2

DATABASE B
users:
id name  profile_id
 1 elvis          1
 2 black          2

profile_id:
id email user_id 
 1 b@g.c       1  
 2 d@g.c       2

I want to merge
users:
id name profile_id
 1 jhon          1 
 2 smith         2
 3 elvis         3
 4 black         4

profile_id:
id email user_id 
 1 a@g.c       1
 2 c@g.c       2
 3 b@g.c       3
 4 d@g.c       4
Assuming one the same database server:

Step 1:

Take a record of the maximum ids for users and profile_id and assume that greater than this is the value copied (they are auto_increment right?).

SELECT MAX(id) INTO @maxuserid FROM A.user;
SELECT MAX(id) INTO @maxprofileid FROM A.profile_id;


Step 2: 

copy the names, and we temporary use the profile_id as the reference to the B.id:

INSERT INTO A.users ( name, profile_id)
SELECT users.name, users.id FROM B.users


Step 3:

Same for profile_id, using user_id as the temporary old id.

INSERT INTO A.profile_id (email, user_id)
SELECT profile_id.email, profile_id.id FROM B.profile_id


Step 4:

Now correct the A.user.profile_id and A.profile_id.user_id base on the mappings that exist in table B:

UPDATE A.user AS auser
       JOIN B.user AS buser,
            ON auser.profile_id = buser.id
       JOIN B.profile_id AS bprofile
            ON bprofile.user_id = buser.id
       JOIN A.profile_id AS aprofile,
            ON aprofile.user_id = bprofile.id
SET
   auser.profile_id = buser.id,
   aprofile.user_id = auser.id
WHERE
   auser.id &gt; @maxuserid
   AND aprofile &gt; @maxprofileid


tip: write the above UPDATE as SELECT to make sure I've got the join criteria correct.