0

我想要表记录如下:

---------------------------------------------------------------------------
id | receiver_user_id | sender_user_id | message_text | insertdate
---------------------------------------------------------------------------
6  | 33               | 42             | OLD          | 2013-05-08 10:08:53
8  | 33               | 43             | ddddd        | 2013-05-07 19:01:45
7  | 33               | 38             | Ipsum        | 2013-04-25 10:27:35
---------------------------------------------------------------------------

我正在使用这个查询:

SELECT *
FROM (`player_messages`)
WHERE `receiver_user_id` =  '33'
GROUP BY sender_user_id
ORDER BY `player_messages`.`insertdate` DESC

并获取如下表记录。

---------------------------------------------------------------------------
id | receiver_user_id | sender_user_id | message_text | insertdate
---------------------------------------------------------------------------
6  | 33               | 43             | ddddd        | 2013-05-07 19:01:45
4  | 33               | 42             | NEW          | 2013-05-07 10:08:58
7  | 33               | 38             | Ipsum        | 2013-04-25 10:27:35
---------------------------------------------------------------------------

请帮忙。提前致谢。

4

2 回答 2

5

您正在从表中选择所有字段,SELECT *但您仅按 分组sender_user_id,并且非聚合列的值将不受限制且不受 order by 的影响。

你应该这样写你的查询:

SELECT   player_messages.*
FROM     player_messages
WHERE    (receiver_user_id, sender_user_id, insertdate) IN (
           SELECT   receiver_user_id, sender_user_id, MAX(insertdate)
           FROM     player_messages
           WHERE    receiver_user_id='33'
           GROUP BY receiver_user_id, sender_user_id)
ORDER BY player_messages.insertdate DESC

这将返回对于接收者和发送者的每个组合具有最大插入日期的所有 player_messages 行。

于 2013-05-08T10:45:46.870 回答
-3

查询 MySQL 数据库时,只需在查询末尾添加“ORDER BY”,即可按升序或降序对任何字段的结果进行排序。您将使用ORDER BY field_name ASC进行升序排序,或使用ORDER BY field_name DESC进行降序排序。

例如

"SELECT * FROM address ORDER BY name ASC"
于 2013-05-08T10:30:16.900 回答