2012-02-16 85 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 | 
+----+----------+------------+---------+