我想要表记录如下:
---------------------------------------------------------------------------
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
---------------------------------------------------------------------------
请帮忙。提前谢谢。
答案 0 :(得分:4)
您正在选择表SELECT *
中的所有字段,但您只按sender_user_id
进行分组,非聚合列的值将不受管理,也不受订单的影响。
您应该像这样编写查询:
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行。
答案 1 :(得分:-2)
当您查询MySQL数据库时,只需在查询结尾添加“ORDER BY”,即可按升序或降序对任何字段进行排序。您可以使用 ORDER BY field_name ASC 进行升序排序,或使用 ORDER BY field_name DESC 进行降序排序。
例如
"SELECT * FROM address ORDER BY name ASC"