如何将sql查询出来的结果集对表进行更新 | 您所在的位置:网站首页 › sql查询结果顺序会变化 › 如何将sql查询出来的结果集对表进行更新 |
如何将sql查询出来的结果集对表进行更新
一、需求二、方法(直接写sql,在数据库客户端进行操作)三、方法一不行可以尝试方法二
一、需求
数据库有a,b两张表,需要利用a表中的字段值去更新或填充b表中的字段值,其中a,b表中通常有相同的字段(比如外键)相关联。 二、方法(直接写sql,在数据库客户端进行操作)1.内联视图更新: update (select a.objectid,a.roadname,a.buildunit,a.region,b.organname,b.areacode from pipeproject a left join sys_organization b on a.buildunit=b.organname where a.buildunit is not null and a.region is null) set region=areacode;通常我们更新表数据的sql结构是:update 表名 set 列名 = 某个值 where 更新条件。在mybatis中,我们只需将查询到的结果集foreach一下即可将数据更新到数据库(在mapper.xml文件中,先查询,后更新)。 但是在数据库客户端直接操作用上述所示语法则可以达到相同的效果。此结构是:update 关联查询结果 set 要更新的列region = 作为替换数据的列areacode。 其中region字段属于表a,areacode字段属于表b。此时所更新成功的表a的记录数为表a和表b进行关联查询结果的记录数,即此更新语句相当于是利用查询得到的结果对表a进行更新,因此尽管sql语句最后没有where子句,也不会对a表进行全表更新! 2.子查询更新: update pipeproject a set a.parentid = (select b.projectid from project b where a.roadname=b.projectname) where a.szplanid='95c112cd72274fbf9dd6d68b19e30023' and a.parentid is null and a.buildtype='1';更新表a中 a.szplanid=‘95c112cd72274fbf9dd6d68b19e30023’ and a.parentid is null and a.buildtype=‘1’ 的数据 的 parentid 字段, parentid 的值从表b中取。 三、方法一不行可以尝试方法二 |
CopyRight 2018-2019 实验室设备网 版权所有 |