UPDATE users, (SELECT users.`id` uid, MAX(COALESCE(replies.ts, messages.ts)) lastt  FROM messages LEFT JOIN replies ON messages.`message_id`=replies.`message_id` LEFT JOIN users ON users.id=messages.user_id GROUP BY users.`id`) res SET users.lastmessage = res.lastt WHERE users.`id` = res.uid;
