Skip to content
Advertisement

Mysql: Update field of most latest record

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement