I like to do something like this:
UPDATE articles
SET live = 1
WHERE aid=3
ORDER BY created DESC
LIMIT 1
The newest article should be live. This is often required in my little CMS. But this query returns an error:
#1221 - Incorrect usage of UPDATE and ORDER BY
Is it not allowed to use ORDER BY or LIMIT in UPDATE queries?
I tried it with a subquery:
UPDATE articles
SET live=1
WHERE id= (SELECT id FROM articles WHERE aid=3 ORDER BY created DESC LIMIT 1)
But this isn’t allowed, too…You must not use the same table in UPDATE and SELECT queries in one query…
What’s the solution? I don’t want to create a TMP table, because this needs to be done often. Is a PHP workaround necessary?
It just plainly works, the only limit is you can only use a single table in the update, not multiple ones (joins and the like). See the the docs. If you need it really bad with a multiple table statement, you can use a LEFT JOIN to the same table to select only the row for which there is no larger ‘created’ value provided you have a non-nullable column.