LoginSignup
40
13

More than 3 years have passed since last update.

MySQLで You can't specify target table 'xxxx' for update in FROM clause を回避する方法

Posted at

問題が発生...

select文の結果をwhere区に使おうとすると

You can't specify target table 'syainTbl' for update in FROM clause 

というエラーが発生。元々のSQL文は以下

update
    syainTbl
set 
    status = 999
where
    user_id in
    (select
        user_id
     from
     syainTbl where status = 2);

syainTblというテーブルのstatusというカラムの値が2のレコードのstatusを999に変更したい、
という文である。

原因

どうやらMySQLでは同一テーブルのサブクエリからのUPDATE文はエラーが発生する模様。
上記の文では、where区内のサブクエリにsyainTblを使用しているため、syainTblのカラムはupdateできない
ということらしい。

解決方法

以下の通り、select文でラップしてaliasを付けてあげるとうまくいく。

update
    syainTbl
set 
    status = 999
where
    user_id in
    (select
        user_id
     from
     (select user_id from syainTbl where status = 2)tmp);

where区の副問合せに直接テーブル名が指定されていなかったらOK、ってことなんでしょうか。

40
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
13