? 在MySQL中胁镐,寫(xiě)SQL語(yǔ)句的時(shí)候圾另,遇到Y(jié)ou can't specify target table '表名' for update in FROM clause這樣的錯(cuò)誤霸株,它的意思是說(shuō),不能先select出同一表中的某些值集乔,再u(mài)pdate這個(gè)表(在同一語(yǔ)句中)去件,即不能依據(jù)某字段值做判斷再來(lái)更新某字段的值。
實(shí)例如下語(yǔ)句:
update t_user set password =(select t.password from t_user t where t.username = 'admin') where uid = '1'
語(yǔ)義是沒(méi)有問(wèn)題的扰路,將id為1的密碼設(shè)置為和admin相同的密碼尤溜,運(yùn)行時(shí)報(bào)錯(cuò)如下:
update t_user set password = (select t.password from t_user t where t.username = 'admin') where uid = '1'
Error Code: 1093. You can't specify target table 't_user' for update in FROM clause 0.000 sec
主要原因是MySQL不支持這種查詢修改的方式,針對(duì)此類問(wèn)題有個(gè)簡(jiǎn)單的解決辦法汗唱,繞一下將查詢結(jié)果放到臨時(shí)表中進(jìn)行取值和更新宫莱,本例修改后語(yǔ)句如下:
update t_user set password = (select a.password from
(select t.password from t_user t where t.username = 'admin') a)
where uid = '1';
運(yùn)行成功,其實(shí)就是將SELECT出的結(jié)果再通過(guò)中間表SELECT一遍哩罪,這樣就避免了錯(cuò)誤授霸。