update同一张表的例子

场景:

业务中台--的bd_area表需要把pk_parent(父id)字段更新

解决sql:

-- 二级更新

update bd_area a LEFT JOIN

(select b.id,substr(b.area_code,1,2) as bcode,substr(b.tree_code,1,3) as btcode from bd_area b where LENGTH(b.tree_code)=3) m

on substr(a.area_code,1,2)=m.bcode and substr(a.tree_code,1,3)=m.btcode

set a.pk_parent=m.id

where LENGTH(a.tree_code)=6

-- 三级更新

update bd_area a LEFT JOIN

(select b.id,substr(b.area_code,1,4) as bcode,substr(b.tree_code,1,6) as btcode from bd_area b where LENGTH(b.tree_code)=6) m

on substr(a.area_code,1,4)=m.bcode and substr(a.tree_code,1,6)=m.btcode

set a.pk_parent=m.id

where LENGTH(a.tree_code)=9

解决思路:

1.最开始的思路是根据areacode和treecode作为关联更新批量更新sql

update bd_area a

set a.pk_parent=(select b.id from bd_area b where LENGTH(b.tree_code)=3

and substr(a.area_code,1,2)=substr(b.area_code,1,2) and substr(a.tree_code,1,3)=substr(b.tree_code,1,3)

where LENGTH(a.tree_code)=6

报错:You can't specify target table 'table name' for update in FROM clause

(不能先将select出表中的某些值,再update这个表(在同一语句中)

问了度娘:

方案一:

多嵌套一度层子知查询,再进行删除道

方案二:

创建一张临时表

经测试:

方案一没作用(delete数据可能会有作用,但是我的update语句不好使)

方案二太复杂

2.突发奇想搜了以下内容:

“update查询条件跟修改字段都在同一张表”

找到一篇文章

https://blog.csdn.net/qq_37709240/article/details/80049744

 update  表1  a1  inner join  (select 字段1,字段2 from 表1 where 条件) a2 on 条件

        set   a1.字段1 = a2.字段2 

 哇,这个思路厉害了啊  先造出来一个虚拟表,然后通过更新虚拟表的方式去实现具体的更新;

在结合我的sql:

update bd_area a LEFT JOIN

(select b.id,substr(b.area_code,1,2) as bcode,substr(b.tree_code,1,3) as btcode from bd_area b where LENGTH(b.tree_code)=3)

on substr(a.area_code,1,2)=b.bcode and substr(a.tree_code,1,3)=b.btcode

set a.pk_parent=b.id

where LENGTH(a.tree_code)=6

报错:Every derived table must have its own alias

每一个派生出来的表都必须有一个自己的别名

3.最后我加个别名m

update bd_area a LEFT JOIN

(select b.id,substr(b.area_code,1,2) as bcode,substr(b.tree_code,1,3) as btcode from bd_area b where LENGTH(b.tree_code)=3) m

on substr(a.area_code,1,2)=m.bcode and substr(a.tree_code,1,3)=m.btcode

set a.pk_parent=m.id

where LENGTH(a.tree_code)=6

完美解决

最后附上get的点:

1.update同一张表的其中一种解决思路是(适应某些场景,自己去品)

update  表1  a1  inner join  (select 字段1,字段2 from 表1 where 条件) a2 on 条件

        set   a1.字段1 = a2.字段2 

先造出来一个虚拟表,然后通过更新虚拟表的方式去实现具体的更新;

2.错误:Every derived table must have its own alias

在做多表查询,或者查询的时候产生新的表的时候会出现这个错误:Every derived table must have its own alias(每一个派生出来的表都必须有一个自己的别名)。

参考:https://blog.csdn.net/qq_32863631/article/details/83024322

3.错误:You can't specify target table 'table name' for update in FROM clause

大致意思是,在同一语句中,不能先select出同一表中的某些值,再update这个表。

参考:https://www.cnblogs.com/pcheng/p/4950383.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值