2012-02-16 87 views
0

下面的SELECT语句如何使查询GROUP BY X DESC

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返回该行,但它dosent它返回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 
+0

你能不能改一下这个问题吗?也许你试图实现的一个例子列表结果 – 2012-02-16 10:12:27

+0

为什么你在这里使用'GROUP BY'? – piotrm 2012-02-16 10:20:42

+0

我使用GROUP BY,因为我想要每个senderID的最后一行。 – Ben 2012-02-16 10:25:20

回答

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将简单地从组中返回一个随机行)。

1

这是不可能的。你必须做一些事情,如:

[...] WHERE `id` = (SELECT MAX(`id`) FROM `messages` WHERE `receiverID` = '5') 
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将根据内部查询中的行的顺序进行分组。

+0

这几乎奏效了..是的,它获取senderID的最后一行,但senderID只有一行,在组出现在分组行之后 – Ben 2012-02-16 10:41:25

+0

啊我准备发表评论,您可以订购外部查询,wasn 100%清楚你后面到底是什么。很高兴看到它的帮助。 – 2012-02-16 11:23:33

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 
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 | 
+----+----------+------------+---------+