您可以将 SQL 与子查询一起使用,例如:
SELECT
messages.*,
max_stamps.max_stamp
FROM
(SELECT
MAX(timestamp) as max_stamp,
`from`
FROM
messages
WHERE
messages.`to`=$currentUser
GROUP BY
`from`
) as max_stamps
LEFT JOIN
messages
ON messages.`from`=max_stamps.`from`
AND max_stamps.max_stamp=messages.timestamp
-ie首先在子查询中选择最大时间戳,然后将它们用于主表。
(更新)如果你想获得最大值id
,然后使用它MAX()
:
SELECT
messages.*,
max_ids.max_id
FROM
(SELECT
MAX(id) as max_id,
`from`
FROM
messages
WHERE
messages.`to`=$currentUser
GROUP BY
`from`
) as max_ids
LEFT JOIN
messages
ON messages.`from`=max_ids.`from`
编辑:误解id
和from
含义to
。提示:用 MySQL 保留字命名表/列可能会引起麻烦(至少你必须用反引号括起来)。