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
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
)
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;
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/
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';