【问题标题】:how can I display the last messages of all users?如何显示所有用户的最后一条消息?
【发布时间】:2021-08-21 14:39:19
【问题描述】:

我想显示用户与其他用户之间的最后一次对话(消息)以及其他用户的姓名和头像。 Whatsapp 和 Messenger 主页是我想要实现的典型示例。

我有 2 个表:用户表和聊天表

用户表

user_id     username      photo
    1        elexis        img
    2        rooney        img
    3        wayne         img

聊天表

   id     user_id       friend_id       message         msg_time
    1        1             2             hello        21-08-19 04:00
    2        2             1             i'm good     21-08-19 04:00
    3        3             1             hey          21-08-19 04:00

elexis 的预期结果应该是:

 1   2    I'm good  **promise**  img    21-08-19 04:00
 1   3    hey       **wayne**    img    21-08-19 04:00

promise 的预期结果应该是:

 1   2    I'm good  **elexis**  img    21-08-19 04:00

但是,我得到的是:

1   2    hello  **promise**  img    21-08-19 04:00
2   1    hello  **elexis**   img    21-08-19 04:00
2   1    I'm good  **promise**  img    21-08-19 04:00
1   2    I'm good  **elexis**   img    21-08-19 04:00
3   1    hey       **wayne**    img    21-08-19 04:00
1   3    hey       **elexis**   img    21-08-19 04:00

我的代码是这样的:

SELECT c.*, u.username, 
FROM users u 
INNER JOIN (
  SELECT user_id, friend_id,id, message 
  FROM chat 
  WHERE user_id = 1 OR friend_id = 1 
  UNION SELECT friend_id, user_id,id, message 
  FROM chat 
  WHERE friend_id = 2 OR user_id = 2 
  ORDER BY id DESC) c 
ON c.friend_id = u.user_id

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    你可以使用:

    select c.*
    from chat c
    where 1 in (c.friend_id, c.user_id) and
          c.msg_time = (select max(c2.msg_time)
                        from chat c2
                        where (c.friend_id, c.user_id) in ( (c2.friend_id, c2.user_id), (c2.user_id, c2.friend_id) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2021-04-17
      • 2019-09-23
      相关资源
      最近更新 更多