The target table for updates cannot be specified in the FROM clause
P粉354602955
2023-08-27 14:46:57
<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>
You can do this in three steps:
...
or
The problem is that, for whatever stupid reason, MySQL doesn't let you write a query like this:
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 belowThis 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: