MYSQL update with WHERE SELECT subquery error

后端 未结 4 1290
时光取名叫无心
时光取名叫无心 2020-12-05 02:46

I have an issue with getting select sub-queries to work on an UPDATE. I\'m trying something like the following:

UPDATE foo
   SET bar=bar-1
 WHE         


        
相关标签:
4条回答
  • 2020-12-05 02:56

    From this web article

    The reason for this error is that MySQL doesn’t allow updates to a table when you are also using that same table in an inner select as your update criteria. The article goes on to provide a solution, which is to use a temporary table.

    Using this example, your update should be this:

    update foo
    set bar = bar - 1
    where baz in
    (
      select baz from
      (
        select baz
        from foo
        where fooID = '1'
      ) as arbitraryTableName
    )
    
    0 讨论(0)
  • 2020-12-05 03:15

    Because of error 1093 Error 1093 (ER_UPDATE_TABLE_USED) SQLSTATE = HY000. The work around is to create a temporary table.

    CREATE TEMPORARY table foo_bak (SELECT baz from foo WHERE fooID='1');
    
    UPDATE foo
      SET foo.bar=foo.bar-1
    WHERE foo.baz =
      (
        SELECT baz
        FROM foo_bak
      );
    
    DROP TABLE foo_bak;
    
    0 讨论(0)
  • 2020-12-05 03:19

    So far as I know, when updating a table, Mysql locks it in order to do a safe update. You cannot select data and update the same table as you're trying.

    Those texts should help you

    • http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

    • http://verysimple.com/2011/03/30/mysql-cant-specify-target-table-for-update-in-from-clause/

    0 讨论(0)
  • 2020-12-05 03:20

    In some cases you can also take advantage of the MySQL variable. e.g.:

    SET @id1 = (SELECT id FROM foo WHERE name = 'parent');
    UPDATE foo SET parent_id = @id1 WHERE name = 'emails';
    
    0 讨论(0)
提交回复
热议问题