需求

通过 form_id 分组,根据 timestamp 查询最新一条 message。

表结构

id | from_id | to_id | subject | message | timestamp

SQL

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;