SQL报1093错误You can’t specify target table for update in FROM clause

admin
admin
admin
376
文章
102
评论
2021年10月23日09:59:03
评论
3,869

SQL报1093错误You can’t specify target table for update in FROM clause

最近在使用sql语句进行更新数据的时候报出以下错误:

#1093,You can't specify target table for update in FROM clause

错误1093的意思是:不能先select出同一表中的某些值,再update这个表(在同一语句中);此问题仅在Mysql中出现,Oracle数据库中则中无此问题。

举例说明:

update description set showcase_flag=1 where description.link in  (SELECT link FROM description where showcase_flag="是") ;

上述代码from后面跟的表description和update后面的表description是同一张表,这在sql语法里面是不允许的。所以会爆出#1093,You can't specify target table for update in FROM clause的错误,所以需要改为下面的代码:

第一种方法:涉及到as语法,用别名解决

实例1:
update description set showcase_flag=1 where description.link in (SELECT a.link FROM (SELECT link FROM description where showcase_flag="是")  as a);

实例2:
update wp_posts set post_content = REPLACE(post_content,"old","new")
where id in (select a.id from (select id from wp_posts,wp_term_relationships,wp_term_taxonomy 
where ID=object_id) as a)

主要是是后面的语句,where 字段1 in (select a.字段1 from (正常select语句) as a),a是临时创建的一个表,不会创建在数据库中,as语句只能写在后面。

第二种方法:用case when 条件1 then 结果1 when 条件2 then 结果2.......else 结果x end

update description a set a.showcase_flag = case when a.showcase_flag = '是' then '1' when a.showcase_flag = '否' then '0' end;

以上两种代码都可以解决#1093,You can't specify target table for update in FROM clause的错误,大家可以灵活运用。

admin
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: