Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL UPDATE query where id is highest AND field is equal to variable

Tags:

mysql

I'm trying to construct a MySQL query that will UPDATE a row in my table WHERE the id is highest AND a field called idSession is equal to 65. It looks like this:

UPDATE `History` 
SET `state` = 0 
WHERE `id` = (SELECT MAX(id) FROM `History` WHERE `idSession` = 65);

And I'm getting the error message:

"Error Code: 1093. You can't specify target table 'History' for update in FROM clause".

Anyone know what's wrong with my syntax?

like image 570
aadu Avatar asked Jul 11 '12 13:07

aadu


People also ask

How do I get maximum ID records in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

Can we use limit in UPDATE query MySQL?

Yes, it is possible to use UPDATE query with LIMIT in MySQL.


1 Answers

Exactly what it says: You can't select from a table when you're updating that same table based on a condition from the exact same table. (That's intentionally confusingly written :p)

Try this:

UPDATE `History` SET `state`=0 WHERE `idSession`=65 ORDER BY `id` DESC LIMIT 1

You can use ORDER and LIMIT in UPDATE and DELETE queries ;)

like image 95
Niet the Dark Absol Avatar answered Oct 21 '22 08:10

Niet the Dark Absol