2017-06-21 41 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

相关问题