【问题标题】:Merge Database with duplicate primary keys and foreign keys合并具有重复主键和外键的数据库
【发布时间】:2016-03-08 07:03:17
【问题描述】:

我们有两个需要合并的 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

blue lines我要加入员工姓名吗?

Sql fiddle link

任何建议将不胜感激。

【问题讨论】:

  • 您是否有一种算法方法可以知道该做什么?在这种情况下,您总共可以在不到 4 个 SQL 中完成所有操作。否则,请一次执行INSERT ... SELECT ...。您在拼写 SQL 方面需要帮助吗?
  • 是的。@RickJames AKA MR Spelling。我需要知道如何解决“在两个数据库中使用不同的 staff_id 重复员工”我要加入员工姓名吗?

标签: mysql sql merge phpmyadmin myisam


【解决方案1】:
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

【讨论】:

  • SELECT ... FROM db1.tbl a JOIN db2.tbl b ON a.staff_name = b.staff_name WHERE db1.Staff_id != db2.Staff_id -- 两个表中都存在员工 ID 不匹配
猜你喜欢
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 2013-12-19
  • 2013-04-30
  • 1970-01-01
  • 2022-11-25
相关资源
最近更新 更多