gpt4 book ai didi

mysql根据源数据动态插入

转载 作者:行者123 更新时间:2023-11-29 07:18:33 24 4
gpt4 key购买 nike

我有下表,表名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

该数据表示要插入“表”列中提到的表中的数据的映射。 “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”表编写查询来生成此类插入语句?

最佳答案

将来,附加 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);

这是你想要的吗?

关于mysql根据源数据动态插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37006263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com