如何查询GROUP BY x DESC

时间:2012-02-16 10:07:46

标签: mysql sql group-by sql-order-by

以下SELECT语句

select * 
from messages 
where receiverID = '5' 
group BY senderID 
order by id DESC

数据库:

id | senderID | receiverID | message
1  |  245     |    5       | test 1
2  |  89      |    5       | test 2
3  |  79      |    5       | test 3
4  |  245     |    5       | test 4
5  |  245     |    5       | test 5

对于senderID = 245,我希望返回id = 5的行,但是它会返回id = 1的行,但我想要最后一行。如何实现?

返回:

id | senderID | receiverID | message
1  |  245     |    5       | test 1
2  |  89      |    5       | test 2
3  |  79      |    5       | test 3

哦,我做到了:D

所以对于有类似问题的人来说,这是有用的代码

     SELECT * FROM ( SELECT * FROM messages WHERE
 receiverID = '5' ORDER BY id DESC) AS m GROUP BY senderID ORDER BY id DESC

5 个答案:

答案 0 :(得分:1)

这是不可能的。你必须做类似的事情:

[...] WHERE `id` = (SELECT MAX(`id`) FROM `messages` WHERE `receiverID` = '5')

答案 1 :(得分:1)

就个人而言,我会考虑一个子查询,根据这一点,应该为你做的工作

SELECT messagesOrdered.*
FROM (
  SELECT * 
  FROM messages 
  WHERE receiverID = '5' 
  ORDER BY id DESC
) AS messagesOrdered
GROUP BY senderID

您可能希望检查已设置的键,具体取决于表的大小。

使用MAX的问题在于,如果在id字段上使用MAX,那么它将获得您要查找的数字,但是在另一个字段上使用MAX时,不会获得与该ID匹配的数据。使用子查询方法,内部查询正在进行排序,然后外部的GROUP将根据内部查询中的行顺序进行分组。

答案 2 :(得分:1)

SELECT * FROM messages m
JOIN 
( SELECT senderID, MAX(id) AS last
  FROM messages 
  WHERE receiverID = '5' 
  GROUP BY senderID ) mg
ON m.id = mg.last

答案 3 :(得分:0)

我不确定我完全理解你的问题,但听起来像你想要的那样:

select max(id), 
       senderId, 
       max(receiverId), 
       max(message)
from messages 
where receiverID = '5' 
group BY senderID 
order by id DESC

请注意,您还需要在聚合中包含消息,否则您将获得不可预测的结果(其他DBMS不允许遗漏max(message)但MySQL只会从组中返回一个随机行)

答案 4 :(得分:0)

这是我的:)

select m1.* from messages m1
left join messages m2
on m1.senderid = m2.senderid and m1.id < m2.id
where m2.id is null and receiverID = '5' 

鉴于你的例子,这将返回:

+----+----------+------------+---------+
| ID | SENDERID | RECEIVERID | MESSAGE |
+----+----------+------------+---------+
|  2 |       89 |          5 | test 2  |
|  3 |       79 |          5 | test 3  |
|  5 |      245 |          5 | test 5  |
+----+----------+------------+---------+