mysql动态插入基于源数据

时间:2016-05-03 13:55:58

标签: mysql

我有下表,表名为source_data

column1    values     table  col        group_flag   index
--         --         --     --         --           --    
id         1          users  oid        1            1
fName      dan        users  firstName  0            1
lName      opera      users  lastName   0            1
oid        2          users  oid        1            2
fName      fan        users  firstName  0            2
lName      popa       users  lastName   0            2
id         3          users  oid        1            3
fName      oana       users  firstName  0            3 
lName      jon        users  lastName   0            3

该数据表示要插入表#34;表"中提到的表中的数据的映射。 " group_flag"表示应将哪些列数据分组。

因此,根据这些数据,我需要"用户"表3记录,如

insert into users (oid,firstName,lastName) values (1,'dan','opera');
insert into users (oid,firstName,lastName) values (2,'fan','popa');
insert into users (oid,firstName,lastName) values (3,'oana','jon');

如何从" source_data"编写查询表生成这样的插入语句?

1 个答案:

答案 0 :(得分:2)

将来,请附上DDL以便于解释。检查我的解决方案

DDL

CREATE TABLE tmp (
  column1 VARCHAR(11),
  `values` VARCHAR(11),
  `table` VARCHAR(11),
  col VARCHAR(11),
  group_flag INT,
  `index` INT
);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('id','1','users','oid',1,1);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('fName','dan','users','firstName',0,1);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('lName','opera','users','lastName',0,1);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('oid','2','users','oid',1,2);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('fName','fan','users','firstName',0,2);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('lName','popa','users','lastName',0,2);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('id','3','users','oid',1,3);
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('fName','oana','users','firstName',0,3); 
INSERT INTO tmp(column1,`values`,`table`,col,group_flag,`index`) VALUES('lName','jon','users','lastName',0,3);

查询

select concat("insert into ",`table`,"(",GROUP_CONCAT(col),') VALUES (',GROUP_CONCAT(`values`),');') from tmp group by `index`,`table`

结果

insert into users(oid,firstName,lastName) VALUES (1,dan,opera);
insert into users(oid,firstName,lastName) VALUES (2,fan,popa);
insert into users(oid,firstName,lastName) VALUES (3,oana,jon);

这是你想要的吗?