php – 从表中查找最新消息,由用户在mysql中分组

我的网站上有一个私人消息表,有一段时间我现在有一个收件箱和发送箱分开.我想将收件箱/发送箱组合在一起,只向特定用户显示最新消息.

TLDR:我想显示通过发送到每个用户或从每个用户发送的最新消息.

表的例子

|  id | fromuser | fromid | touser | toid | message    |  timestamp            |
--------------------------------------------------------------------------------
|  1  | user1    |  1     | user2  |  2   | Hello..    |  2015-01-01 00:00:00  |
|  2  | user1    |  1     | user3  |  3   | okay...    |  2015-01-02 00:00:00  |
|  3  | user3    |  3     | user1  |  1   | not....    |  2015-01-03 00:00:00  |
|  4  | user2    |  2     | user3  |  3   | New....    |  2015-01-04 00:00:00  |
|  5  | user2    |  2     | user1  |  1   | With.....  |  2015-01-05 00:00:00  |
--------------------------------------------------------------------------------

结果我在用户1中寻找

|  id | fromuser | fromid | touser | toid | message    |  timestamp            |
--------------------------------------------------------------------------------
|  3  | user3    |  3     | user1  |  1   | not....    |  2015-01-03 00:00:00  |
|  5  | user2    |  2     | user1  |  1   | With.....  |  2015-01-05 00:00:00  |
--------------------------------------------------------------------------------

使用下面的代码我可以让它向每个用户显示一条消息,但它显示最旧的消息而不是最新消息.

mysql_query("SELECT m1.*, users.id AS userid, users.username 
    FROM pm AS m1, pm AS m2, users 
    WHERE ((m1.fromuser='".$_SESSION['userName']."' AND users.id=m1.toid) 
    OR (m1.touser='".$_SESSION['userName']."' AND users.id=m1.fromid)) 
    AND m2.id=m1.id ORDER BY timestamp DESC");

解决方法:

试试这个:

 
    选择 *
      来自消息m
      哪里不存在(
        选择1
          来自消息mm
          其中(mm.fromuser = m.fromuser或mm.fromuser = m.touser)AND(mm.touser = m.touser或mm.touser = m.fromuser)
            和mm.timestamp> m.timestamp
        )
        和m.fromuser =’user1’或m.touser =’user1′;

demo here.

将两个用户之间的对话标记为特定对话可能会更好,然后每条消息都属于一个对话,因此查找用户参与的对话变得更加容易,以及与此相关的消息的信息变得更加容易.会话.无论如何.

试试这个.啊.

select m.* 
  from messages m 
     left join messages m2 
       on ((m.fromuser = m2.fromuser and m.touser = m2.touser) 
           or (m.fromuser = m2.touser and m.touser = m2.fromuser)) 
         and m.timestamp < m2.timestamp 
  where (m.fromuser = 'user1' or m.touser = 'user1') 
  and m2.id is null;

它可能优于不存在的版本,即使我设法修复那个版本.

this fiddle actually works

上一篇:c# – 如何将消息从子用户控件传递给父用户


下一篇:AMQP_1.0_PR2学习笔记