解决mysql You can't specify target table for update in FROM clause错误

mysql中You can't specify target table for update in FROM clause错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)。

例①如下面这个sql:

代码如下:

delete from tbl where id in  

        select max(id) from tbl a where EXISTS 
        ( 
            select 1 from tbl b where a.tac=b.tac group by tac HAVING count(1)>1 
        ) 
        group by tac 

 

改写成下面就行了:

 

代码如下:

delete from tbl where id in  

    select a.id from  
   
        select max(id) id from tbl a where EXISTS 
        ( 
            select 1 from tbl b where a.tac=b.tac group by tac HAVING count(1)>1 
        ) 
        group by tac 
    ) a 

 

也就是说将select出的结果再通过中间表select一遍,这样就规避了错误。

注意,这个问题只出现于mysql,mssql和oracle不会出现此问题。

 

You can't specify target table for update in FROM clause含义:不能在同一表中查询的数据作为同一表的更新数据。

例②:

我想查询t_user_asset的余额加上50000作为更新字段f_cashAmount的值,这样写是不行的

 
  1. UPDATE t_user_asset SET f_cashAmount =   
  2.     (  
  3.      SELECT (ua.f_cashAmount+50000) cashAmount FROM t_user_asset ua WHERE ua.f_userId = 290  
  4.   )  
  5. WHERE f_userId = 290  

修改成以下写法就行,意思就是变个方向,在select外边套一层,让数据库认为你不是查同一表的数据作为同一表的更新数据:

 

 
  1. UPDATE t_user_asset SET f_cashAmount =   
  2. (  
  3.   SELECT ub.cashAmount FROM  
  4.         (  
  5.              SELECT (ua.f_cashAmount+50000) cashAmount FROM t_user_asset ua WHERE ua.f_userId = 290  
  6.         ) ub  
  7. )  
  8. WHERE f_userId = 290  


以上问题只针对mysql数据库 

例③:https://pintia.cn/problem-sets/1375423976918028288/problems/1375424236121960453

 

 

 

 mysql下错解:


update orderdetails
set unitprice = unitprice - 1
where Quantity in
(select min(Quantity)from orderdetails)

 

正解:

update orderdetails
set unitprice = unitprice - 1
where Quantity in
(select av from (select min(Quantity) av from orderdetails)as aa)

posted @ 2021-04-20 18:12  huyoo  阅读(4760)  评论(0编辑  收藏  举报