只有在两个列都存在的情况下,才将值从一个表复制到另一个表

时间:2014-10-09 12:04:04

标签: mysql copy

我正在尝试将表从一个数据库复制到另一个数据库,如下所示:

INSERT INTO db1.content SELECT * FROM db2.content;

已添加一些字段,其中一些字段已更改名称。所以我想设置一个条件,只复制两个表中存在的列。

也许是这样的,其中*是列名的通配符。

INSERT INTO db1.content SELECT * FROM db2.content WHERE db1.* = db2.*;

1 个答案:

答案 0 :(得分:1)

您可以按照以下过程执行此操作:table1是源表,table2是目标表:

CREATE DEFINER=`root`@`localhost` PROCEDURE `copySimilarTableContent`(in table1 varchar(50), in table2 varchar(50))
    BEGIN
     drop temporary table if exists tempTable1;
     create temporary table tempTable1
      select column_name from information_schema.columns where `TABLE_SCHEMA`='db2' and table_name=table1;

     drop temporary table if exists tempTable2;
     create temporary table tempTable2
      select column_name from information_schema.columns where `TABLE_SCHEMA`='db1' and table_name=table2;

     set @common_col = (select group_concat(t1.column_name)
          from tempTable1 t1
          left join tempTable2 t2 on t1.column_name = t2.column_name
          where t2.column_name is not null);

     set @sql = concat("insert into ", table2, " (",@common_col,") select ", @common_col, " from ", table1);

      PREPARE stmt FROM @sql;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;


    END