search

Home  >  Q&A  >  body text

The target table for updates cannot be specified in the FROM clause

<p>I have a simple mysql table: </p> <pre class="brush:php;toolbar:false;">CREATE TABLE IF NOT EXISTS `pers` ( `persID` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(35) NOT NULL, `gehalt` int(11) NOT NULL, `chefID` int(11) DEFAULT NULL, PRIMARY KEY (`persID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4; INSERT INTO `pers` (`persID`, `name`, `gehalt`, `chefID`) VALUES (1, 'blb', 1000, 3), (2, 'as', 1000, 3), (3, 'chef', 1040, NULL);</pre> <p>I tried running the following update but only received error 1093: </p> <pre class="brush:php;toolbar:false;">UPDATE pers P SET P.gehalt = P.gehalt * 1.05 WHERE (P.chefID IS NOT NULL OR gehalt < (SELECT ( SELECT MAX(gehalt * 1.05) FROM pers MA WHERE MA.chefID = MA.chefID) AS_pers ))</pre> <p>I searched for the error and found the following page from mysql http://dev.mysql.com/doc/refman/5.1/en/subquery-restrictions.html but that didn't help me. </p> <p>How do I correct the sql query? </p>
P粉354602955P粉354602955475 days ago392

reply all(2)I'll reply

  • P粉237125700

    P粉2371257002023-08-28 13:59:47

    You can do this in three steps:

    CREATE TABLE test2 AS
    SELECT PersId 
    FROM pers p
    WHERE (
      chefID IS NOT NULL 
      OR gehalt < (
        SELECT MAX (
          gehalt * 1.05
        )
        FROM pers MA
        WHERE MA.chefID = p.chefID
      )
    )

    ...

    UPDATE pers P
    SET P.gehalt = P.gehalt * 1.05
    WHERE PersId
    IN (
      SELECT PersId
      FROM test2
    )
    DROP TABLE test2;

    or

    UPDATE Pers P, (
      SELECT PersId
      FROM pers p
      WHERE (
       chefID IS NOT NULL 
       OR gehalt < (
         SELECT MAX (
           gehalt * 1.05
         )
         FROM pers MA
         WHERE MA.chefID = p.chefID
       )
     )
    ) t
    SET P.gehalt = P.gehalt * 1.05
    WHERE p.PersId = t.PersId

    reply
    0
  • P粉481815897

    P粉4818158972023-08-28 13:51:38

    The problem is that, for whatever stupid reason, MySQL doesn't let you write a query like this:

    UPDATE myTable
    SET myTable.A =
    (
        SELECT B
        FROM myTable
        INNER JOIN ...
    )

    That is, if you want to perform UPDATE/INSERT/DELETE operations on the table, you cannot query internally (but you Can reference fields in external tables...)


    The solution is to replace the myTable instance in the subquery with (SELECT * FROM myTable) as shown below

    UPDATE myTable
    SET myTable.A =
    (
        SELECT B
        FROM (SELECT * FROM myTable) AS something
        INNER JOIN ...
    )

    This will obviously cause the necessary fields to be implicitly copied into the temporary table, so this is allowed.

    I found this solution here. Notes for this article:

    reply
    0
  • Cancelreply