关于sql某些字段数据的转移 ----JAVA

最近写一个功能,表的数据需要转移,之前没写过这样的,就记录一下,中间也参考了好多博主的博客,感谢!!!

insert INTO 目标表(字段1, 字段2, ...)SELECT 字段1, 字段2 FROM 来源表 WHERE not exists (select * from 目标表 where 目标表.比较字段 = 来源表.比较字段);

在这里我列举我数据库中的一个实例,希望能帮到看到这篇博客的人!!!

表数据介绍:来源表,目标表1,目标表2(其中目标表1是主表,目标表2是明细表,所以就决定了要先把数据转移到目标表1中)

字段介绍就不那么详细了,主要是辅助作用,看懂sql就可以
来源表字段:id,files_name,files_url…
目标表1:service_id,attachment_type…
目标表2:attachment_id,attachment_url,attachment_source_name…

第一步:先把数据转移到目标表1

insert into sc_attachment(service_id,attachment_type。。。) 
select sc.id, '1'。。。 from  sc_tender_project sc where sc.files_name is not null and not exists (select * from sc_attachment ment1 where ment1.service_id = sc.id)
union
select sc1.id, '2'。。。 from  sc_tender_project sc1 where sc1.boq_name is not null and not exists (select * from sc_attachment ment2 where ment2.service_id = sc1.id)
union
select sc2.id, '3'。。。 from  sc_tender_project sc2 where sc2.priceratio_name is not null and not exists (select * from sc_attachment ment3 where ment3.service_id = sc2.id)
union
select sc3.id, '4'。。。 from  sc_tender_project sc3 where sc3.request_name is not null and not exists (select * from sc_attachment ment4 where ment4.service_id = sc3.id)

可能直接看sql有点不明白,我解释一下,也可以根据自己的需要自定义sql,如果是单纯的转移,可以用文章最上边的语句
需求: 1.需要根据上传不同文件选择不同的上传类型,也就是1,2,3,4。。。
2.同一条数据可能会上传好几种不同类型的文件,然后就不能有重复,所以选择使用union,消除冗余的信息
3.其次,如果目标表中已经存在相对应的数据,那就不需要转移,所以用到not exists去重(可根据需求自定义)

第二步:把数据转移到目标表2

insert into sc_attachment_detail(attachment_id,attachment_url,attachment_source_name)
select ment.id,sc.files_url,sc.files_name。。。 from sc_tender_project sc left join sc_attachment ment on sc.id = ment.service_id where ment.attachment_type=1
union
select ment1.id,sc1.files_url,sc1.files_name。。。 from sc_tender_project sc1 left join sc_attachment ment1 on sc1.id = ment1.service_id where ment1.attachment_type=2
union
select ment2.id,sc2.files_url,sc2.files_name。。。 from sc_tender_project sc2 left join sc_attachment ment2 on sc2.id = ment2.service_id where ment2.attachment_type=3
union
select ment3.id,sc3.files_url,sc3.files_name。。。 from sc_tender_project sc3 left join sc_attachment ment3 on sc3.id = ment3.service_id where ment3.attachment_type=4

解释一下,可以根据自己的需要自定义sql,如果是单纯的转移,可以用文章最上边的语句
需求: 1.需要用到两张表的数据,所以联合查询,加上此定义的一些条件
2.同一条数据可能会上传好几种不同类型的文件,然后就不能有重复,所以选择使用union,消除冗余的信息

总结:以上就是我的解决方案,记录一下,如果有不对的地方,请指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值