specify target table for update in FROM clause

mysql的You can't specify target table '***' for update in FROM clause

student表

student表

  • 目的sql語句

查詢student表中年齡最大的,並將它的name改成"十五歲"mysql

  • 第一時間我想到的sql語句是
update 表名 set name = 十五歲 
where age = ( select max(age) from 表名)

結果運行時報異常:You can't specify target table 'student' for update in FROM clausesql

這個異常的意思就是spa

第二層查詢的FROM子句中的表,不能做爲更新的目標表。即不能對同一張表的查詢結果做爲本表增刪改的判斷條件code

  • 那麼接下來我就想到,講查詢結果設置成中間表,而後進行where的判斷
update 表名 set name = 十五歲 
where age =( select t.age from ( select max(age) as num from 表名) t)

 

總結

即不能對一張表的查詢結果做爲本表增刪改的判斷條件blog

select出的結果再經過中間表select一遍,這樣就規避了錯誤。ci

相關文章
相關標籤/搜索