【问题标题】:How to merge 2 tables with different structures into 1 table using MySQL?如何使用 MySQL 将 2 个不同结构的表合并为 1 个表?
【发布时间】:2014-07-22 04:51:37
【问题描述】:

我这里有 2 个表需要合并。

表1 PK1 appt_id other_fields_here

表2 PK2 appt_id other_fields_here(大部分名称不同,但也有一些与 table1 同名)

该表将使用 appt_id 作为匹配键进行合并。没有匹配的任何记录都会转移到新表中。

请参阅下面的示例,以便更好地了解我想要完成的任务。

非常感谢。


示例:每个表中只有 2 条记录。合并后新表会有3条记录。

scenario1:匹配 appt_id(这将在新表上创建一条记录。)

table1: pk1=1 | appt_id=1 | field1=test1

table2: pk2=1 | appy_id=1 | field2=test1

new pk = autoincrement | appt=1 | field1=test1 | field2=test1

scenario2:appt_id 没有匹配记录(这将在新表中创建 2 条新记录)

table1: pk1=293454 | appt_id=34535 | field1=test34535

table2: pk2=735353 | appt_id=88888 | field2=test88888

new pk = autoincrement | appt=34535 | field1=test34535 | field2=null

new pk = autoincrement | appt=88888 | field1=null | field2=test88888

【问题讨论】:

  • 检查场景1中的列名文本。我觉得你在第二个表中的列名不匹配它应该是 appt_id 而不是 appy_id。

标签: mysql sql


【解决方案1】:

同时使用 join 和 UNION。检查这个demo

SELECT t.appt_id,t.field1,t2.field2 FROM table1 t LEFT JOIN table2 t2 ON t.appt_id = t2.appt_id
UNION
SELECT t2.appt_id,t.field1,t2.field2 FROM table2 t2 LEFT JOIN table1 t ON t.appt_id = t2.appt_id

【讨论】:

    【解决方案2】:

    这东西叫FULL OUTER JOIN

    不幸的是 MySQL 不支持这种连接。

    您可以使用以下查询来模拟它的结果:

    SELECT
      * -- list required fields here!
    FROM
      table1 T1
      LEFT JOIN table2 T2
        ON T1.appt_id
    
    UNION
    
    SELECT
      * -- list required fields here!
    FROM
      table1 T1
      RIGHT JOIN table2 T2
        ON T1.appt_id
    

    【讨论】:

      【解决方案3】:

      insert into new_table(appt_id, field) select appt_id, field1 from table1 union select appt_id, field2 from table2;

      union 将仅从两个表中获取唯一记录。如果您需要所有记录,请使用union all。 我假设当 appt_id 相同时 field1 和 field2 具有相同的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-10
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 2012-04-13
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多