我们有两个需要合并的Mysql数据库(Myisam)。它们都具有相同的结构。目标是使用一个查询将所有项目从一个数据库复制到另一个数据库以执行并进行合并。
情景如下:
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
选择员工姓名不一样的所有重复员工?
Not shown
我们可以按原样附加,并在'copyTo'数据库中将order_items_id
增加10倍,而不是最大order_items_id
。
任何建议都将受到赞赏。
答案 0 :(得分:3)
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