Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: Update field of most latest record

Tags:

I'm trying to update the latest record where name is John (John has multiple records but different ID) but I seem to be in a bind. What's wrong with my query?

UPDATE messages_tbl SET is_unread=1 WHERE ReceiveTime = (SELECT MAX(ReceiveTime) FROM messages_tbl WHERE name='John') 

Is there a better way to do something like this?

like image 367
enchance Avatar asked Mar 30 '13 06:03

enchance


People also ask

How do I UPDATE a field value in MySQL?

MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.

How do you UPDATE the latest row in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.

How do I get the latest row in MySQL?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.


2 Answers

You could try using ORDER and LIMIT.

Try this:

UPDATE messages_tbl SET is_unread = 1 WHERE name = 'John' ORDER BY ReceiveTime DESC LIMIT 1 

This query will update the rows in order of the highest (most recent) ReceiveTime to the lowest (oldest) ReceiveTime. Used in conjunction with LIMIT, only the most recent ReceiveTime will be altered.

like image 59
Aiias Avatar answered Sep 22 '22 07:09

Aiias


You can join both and perform update based on the condition.

UPDATE  messages a         INNER JOIN         (             SELECT  name , MAX(ReceiveTime) max_time             FROM    messages              GROUP   BY name          ) b ON  a.name = b.name AND                 a.ReceiveTime = b.max_time SET     a.is_unread = 1 -- WHERE    a.name = 'John' 

Without the WHERE condition. It will all update the column is_unread for the latest entry.

like image 32
John Woo Avatar answered Sep 23 '22 07:09

John Woo