A Clockwork Noodle

Make such knaveries yours!

Archive for August 2009

MySQL UPDATE self subselect

with one comment

I got stuck moving back to MySQL 4.1 from 5, where I had an UPDATE statement that operated on a subselect from the same table. In 4.1 I got the error “You can’t specify target table ‘x’ for update in FROM clause” due to the self-referring subselect. This syntax allowed me to work around the problem:

UPDATE attributes AS t1,
(SELECT MAX(ordering)+1 AS ordering FROM attributes WHERE parentid='1') AS tt
SET t1.ordering = tt.ordering
WHERE t1.parentid='1' AND t1.ordering='-1'

Here the subselect is stored in a different recordset so MySQL doesn’t mind the self-reference.

Written by greensweater

2009-08-18 at 02:08

Posted in General

Tagged with , , ,

Follow

Get every new post delivered to your Inbox.