Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql in PHP - how to update only one row in table but with greatest id number

Tags:

php

mysql

max

I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like that:

UPDATE table SET name='test_name' WHERE id = max(id)

Unfortunatelly it doesnt work. Any ideas?

Table Structure

id | name
---|------
 1 | ghost
 2 | fox
 3 | ghost

I want to update only last row because ID number is the greatest one.

like image 909
Kalreg Avatar asked Feb 09 '12 23:02

Kalreg


1 Answers

The use of MAX() is not possible at this position. But you can do this:

UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;

For multiple table, as @Euthyphro question, use table.column.
The error indicates that column id is ambiguous.

Example :

UPDATE table1 as t1
LEFT JOIN table2 as t2
       ON t2.id = t1.colref_t2
SET t1.name = nameref_t2
ORDER BY t1.id DESC
LIMIT 1
like image 198
iblue Avatar answered Oct 05 '22 03:10

iblue