2017-06-21 27 views
0

我目前正在嘗試爲我的網站創建某種形式的即時通訊工具,允許用戶彼此溝通。爲此,我創建了一個名爲messages的sql表,標題爲id, senderID, recipientID, timestamp, message僅選擇來自所有結果的最新記錄,其中username = x?

目前,我正在努力研究如何爲id = x的給定用戶創建所有對話的列表(不是單個消息)。此列表應該只包含發送到用戶X的最新消息,從每個發件人Y1,Y2,Y3,...

例如,考慮表

------------------------------------------------------------- 
| ID | senderID | recipientID | timestamp | message | 
------------------------------------------------------------- 
| 1 |  14  |  34  | 2017-06-21 | Hello ... | 
| 2 |  14  |  37  | 2017-06-22 | How ar... | 
| 3 |  11  |  34  | 2017-06-23 | I was ... | 
| 4 |  17  |  34  | 2017-06-24 | Good ... | 
| 5 |  18  |  34  | 2017-06-25 | My na ... | 
| 6 |  11  |  34  | 2017-06-26 | I've ... | 
| 7 |  14  |  34  | 2017-06-27 | Thank ... | 
| 8 |  12  |  34  | 2017-06-28 | I nee ... | 
| 9 |  17  |  34  | 2017-06-29 | Have ... | 
| 10 |  17  |  34  | 2017-06-30 | You h ... | 
------------------------------------------------------------- 

現在,假設我是用戶34,我希望查看包含每個senderID給我自己的最新消息的列表。什麼是SQL查詢會這樣做?即SQL查詢會給出如下結果:

------------------------------------------------------------- 
| ID | senderID | recipientID | timestamp | message | 
------------------------------------------------------------- 
| 5 |  18  |  34  | 2017-06-25 | My na ... | 
| 6 |  11  |  34  | 2017-06-26 | I've ... | 
| 7 |  14  |  34  | 2017-06-27 | Thank ... | 
| 8 |  12  |  34  | 2017-06-28 | I nee ... | 
| 10 |  17  |  34  | 2017-06-30 | You h ... | 
------------------------------------------------------------- 

什麼SQL命令用於給出這個結果?

+1

通過時間戳DESC其中recipientID = 34階 –

回答

0

這裏有一個方法:

select m.* 
from messages m 
where m.recipientId = 34 and 
     m.timestamp = (select max(m2.timestamp) 
        from messages m2 
        where m2.senderId = m.senderId and m2.recipientId = m.recipientId 
        ); 

INEXISTSJOIN/GROUP BY都會做類似的事情。

0

SELECT * FROM messages WHERE recipientId = 34 ORDER BY timestamp DESC;

0

這裏就是我的回答:

  1. 創建一個名爲messages_latest表,列一樣的是表messages;
  2. 當與id = 1信息發送到與用戶id = 34一個用戶,首先從表messages_latest其中senderID = 1recipientId = 34移除消息,然後插入最新記錄到messages_latest;

message_latest保存最近的消息。

0

您可以創建第二個查詢通過recipientIDsenderID得到MAX(timestamp)組,只是與那些相同的字段和ORDER BY timestamp ASCmessages表連接。

這樣,您只會過濾從senderID發送到WHERE子句中指定的recipientID的最後一條消息。

select m.* 
from messages as m 
    join (select recipientID, senderID, max(timestamp) as timestamp 
     from messages 
     group by recipientID, senderID) as l 
    on m.recipientID = l.recipientID 
    and m.senderID = l.senderID   
    and m.timestamp = l.timestamp 
where m.recipientID = 34 
order by m.timestamp asc 

您可以在這裏找到工作SqlFiddle http://www.sqlfiddle.com/#!9/63a42/18