MySQL Group按时间单个结果顺序

时间:2014-01-23 18:42:35

标签: mysql

我正在尝试从已向我发送消息的消息表中获取用户,但每个发件人只需要一个结果,这是creation列的最大值,这是创建消息的时间

SELECT messages.from, account_images.profile, bio.user_full_name
FROM messages
INNER JOIN account_images ON account_images.uuid=messages.from
INNER JOIN bio ON bio.uuid=messages.from
WHERE messages.to='me'
GROUP BY messages.from
ORDER BY messages.creation DESC

最近创建消息的用户必须位于顶部,但使用此代码时不会显示在最顶层。我提到php mysql Group By to get latest record, not first record但没有得到任何东西 有帮助吗?

2 个答案:

答案 0 :(得分:0)

我发现这个mysql文档非常有用,例如:http://dev.mysql.com/doc/refman/5.0/en/example-maximum-row.html

SELECT * 
FROM messages m
LEFT JOIN messages m2 ON m.creation > m2.creation
WHERE m2.creation IS NULL
AND m1.to='me'

答案 1 :(得分:0)

您可以将当前查询编写为...

SELECT DISTINCT messages.from, account_images.profile, bio.user_full_name
FROM messages
INNER JOIN account_images ON account_images.uuid=messages.from
INNER JOIN bio ON bio.uuid=messages.from
WHERE messages.to='me'

哪个效率稍高 - 但正如您将注意到的当前查询一样,它不会按最新消息排序。

这是按照您的要求排序:

SELECT messages.from, account_images.profile, bio.user_full_name
FROM messages
INNER JOIN account_images ON account_images.uuid=messages.from
INNER JOIN bio ON bio.uuid=messages.from
WHERE messages.to='me'
GROUP BY messages.from
ORDER BY MAX(messages.creation) DESC;

可以使用DISTINCT而不是聚合来获得您想要的结果,但它既不高效也不优雅。