MySQL之You can't specify target table for update in FROM clause解決辦法


這篇文章主要介紹了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的值,這樣寫是不行的。

[sql]  view plain  copy
 
  在CODE上查看代碼片 派生到我的代碼片
  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外邊套一層,讓數據庫認為你不是查同一表的數據作為同一表的更新數據:

[sql]  view plain  copy
 
  在CODE上查看代碼片 派生到我的代碼片
  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數據庫






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM