要求 找到mysql数据库中w字段以/cc开头的行,并且删除/cc。首先要找到符合要求的行,这很简单,select 就可以
select * from a where `CODE` like'/cc%'
第二步 更改字段update a set code=substring(code,4,length(code)-3)
Substring 函数 截取字符串函数name = substring(name,4,length(name)-3)
Name 是要截取的字段name,4,意思是从第4个字符开始,length(name)-3返回字段-3的字符,就是说删除前3个字符。
第三步 想办法把两句sql结合起来。
首先想到的 in 语句
update a set code=substring(code,4,length(code)-3) whereid in
(select id from a where `CODE` like'/dc%')
但是不行 报错You can't
specify target table for update in FROM clause错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)。网上说可以在中间再套嵌一个sql 语句,我试了但是不行,好像是5.7以不上支持这样做。
最后使用inner join语句解决
update a inner join (select id from a where `CODE` like '/cc%') t on a.id=t.id set code= substring(code,4,length(code)-3)