【问题标题】:MySQL merge tables with different structureMySQL合并不同结构的表
【发布时间】:2010-12-20 10:48:02
【问题描述】:

我有两个不同结构的数据库。

表 1:

ch_code    ch_def    ch_weight

表 2:

address    ch_code

我需要合并这两个表,所以结构如下:

ch_code    ch_def    ch_weight    address

两个表的行数或行数不同(表1数据较多)。

我应该使用mergeunion.. 别的吗?

谢谢!

【问题讨论】:

  • 嗯,这取决于你想要在结果表上做什么......如果你添加一些示例数据可能会有所帮助。
  • 澄清一下,您的意思是您在同一个数据库中有 2 个表,并且正在寻找将导致您指定的列的查询吗?
  • 是否有与表格相关的列?例如,代表两个表中同一行的 person_id。
  • 是的,同一个数据库中的 2 个表,表 1 和表 2 的 ch_code 相同。
  • 定义“合并”。您的意思是创建一个全新的永久表吗?或者只是将合并的数据检索到应用程序中以供临时使用?

标签: php mysql merge merging-data


【解决方案1】:

这是一个应该处理三种可能情况的解决方案:

  1. t1 中的 ch_code 值不在 t2 中
  2. t2 中的 ch_code 值不在 t1 中
  3. t1 和 t2 中都有一个 ch_code 值

SELECT t1.ch_code, t1.ch_def, t1.ch_weight, '' as address from t1 where not exists (select * from t2 where t2.ch_code = t1.ch_code)

UNION

SELECT t2.ch_code, '' as ch_def, '' as ch_weight, t2.address from t2 where not exists (select * from t1 where t1.ch_code = t2.ch_code)

UNION

SELECT t1.ch_code, t1.ch_def, t1.ch_weight, t2.ch.address from t1 left join t2 on t1.ch_code = t2.ch_code

获得该结果集后,如果您有一个用于容纳合并数据的新表,则可以执行 INSERT INTO。

【讨论】:

  • PS - 任何人都知道获得包含下划线的多行代码块的秘密吗?我不得不接受每一行的反引号。
【解决方案2】:

如果 Table2 仅包含 Table1 中包含的数据(即 Table2 中没有任何不在 Table1 中的数据),您应该能够执行类似的操作(假设 Table3 已经设置):

INSERT INTO TABLE3 (ch_code, ch_def, ch_weight, address)
SELECT Table1.ch_code, Table1.ch_def, Table1.ch_weight, Table2.address
FROM Table1 LEFT JOIN Table2 on Table1.ch_code = Table2.ch_code

(我没有方便的 MySQL 安装,所以你的具体语法可能会有所不同。)

如果表 2 中的数据与表 1 中的数据不匹配(并且您希望保留该数据),则需要 FULL JOIN(如果 MySQL 不支持,则 UNION LEFT JOIN 和 RIGHT JOIN )。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2014-07-22
    • 2018-01-04
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多