Mysql: Update field of most latest record
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.
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.