合并具有重复主键和外键的数据库
Merge Database with duplicate primary keys and foreign keys
我们有两个 Mysql 数据库 (Myisam) 需要合并。他们都有相同的 structure.The 目标是使用一个查询将所有项目从一个数据库复制到另一个数据库以执行并进行合并。
场景如下:
Red lines - Duplicate staff with same staff_id in both databases.
Blue lines - Duplicate staff with different staff_id in both databases.
Black line - Different staff with the same staff_id in both databases.
Not shown - Different staff with unique staff_id
red lines
可以按原样从一个数据库复制到另一个数据库,但是 order_items_id
可以比 'copyTo' 数据库中的最大值 order_item_id 增加 10 .
black lines
Select 所有重复的员工,其中员工姓名不一样?
Not shown
我们可以按原样追加 order_items_id
比 'copyTo' 数据库中的最大值 order_items_id
多 10。
blue lines
我加入员工姓名吗?
如有任何建议,我们将不胜感激。
SELECT ...
FROM db1.tbl a
JOIN db2.tbl b ON a.staff_name = b.staff_name -- exists in both tables
SELECT ...
FROM db1.tbl a
JOIN db2.tbl b ON a.staff_name = b.staff_name
WHERE db1.Staff_id != db2.Staff_id -- exists in both tables staff id's not matching
SELECT ...
FROM db1.tbl a
LEFT JOIN db2.tbl b ON a.staff_name = b.staff_name
WHERE b.staff_id IS NULL -- missing from b (exists only in a)
SELECT ...
FROM db1.tbl b
LEFT JOIN db2.tbl a ON a.staff_name = b.staff_name
WHERE a.staff_id IS NULL -- missing from a (exists only in b)
将仅在source
中的复制到dest
:
SELECT @max := MAX(staff_id) + 10 FROM db1.tbl; -- destination
INSERT INTO db1.tbl
SELECT @max + source.staff_id, source.name, ...
FROM db2.tbl AS source
LEFT JOIN db1.tbl AS dest ON source.staff_name = dest.staff_name
WHERE dest.staff_id IS NULL
我们有两个 Mysql 数据库 (Myisam) 需要合并。他们都有相同的 structure.The 目标是使用一个查询将所有项目从一个数据库复制到另一个数据库以执行并进行合并。
场景如下:
Red lines - Duplicate staff with same staff_id in both databases.
Blue lines - Duplicate staff with different staff_id in both databases.
Black line - Different staff with the same staff_id in both databases.
Not shown - Different staff with unique staff_id
red lines
可以按原样从一个数据库复制到另一个数据库,但是 order_items_id
可以比 'copyTo' 数据库中的最大值 order_item_id 增加 10 .
black lines
Select 所有重复的员工,其中员工姓名不一样?
Not shown
我们可以按原样追加 order_items_id
比 'copyTo' 数据库中的最大值 order_items_id
多 10。
blue lines
我加入员工姓名吗?
如有任何建议,我们将不胜感激。
SELECT ...
FROM db1.tbl a
JOIN db2.tbl b ON a.staff_name = b.staff_name -- exists in both tables
SELECT ...
FROM db1.tbl a
JOIN db2.tbl b ON a.staff_name = b.staff_name
WHERE db1.Staff_id != db2.Staff_id -- exists in both tables staff id's not matching
SELECT ...
FROM db1.tbl a
LEFT JOIN db2.tbl b ON a.staff_name = b.staff_name
WHERE b.staff_id IS NULL -- missing from b (exists only in a)
SELECT ...
FROM db1.tbl b
LEFT JOIN db2.tbl a ON a.staff_name = b.staff_name
WHERE a.staff_id IS NULL -- missing from a (exists only in b)
将仅在source
中的复制到dest
:
SELECT @max := MAX(staff_id) + 10 FROM db1.tbl; -- destination
INSERT INTO db1.tbl
SELECT @max + source.staff_id, source.name, ...
FROM db2.tbl AS source
LEFT JOIN db1.tbl AS dest ON source.staff_name = dest.staff_name
WHERE dest.staff_id IS NULL