我正在尝试将一个表从一个数据库复制到另一个数据库,如下所示:
INSERT INTO db1.content SELECT * FROM db2.content;
添加了一些字段,并更改了一些名称。所以我想设置一个条件,只复制两个表中存在的列。
可能是这样的,其中 *
是列名的通配符。
INSERT INTO db1.content SELECT * FROM db2.content WHERE db1.* = db2.*;
最佳答案
您可以按照以下过程执行此操作,其中 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
关于mysql - 仅在两个表中都存在列的情况下将值从一个表复制到另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26277974/