私人留言系统[收件箱查询]

时间:2016-03-26 19:07:50

标签: php mysql

我有一个名为“message”的表,我想显示用户之间的所有谈话(最后一条消息)

表格结构:

message_id | user_id | recipient_id | message | status | date

示例行:

1 | 1 | 2 | Hello | 0 | 2016-03-26 12:00:00
2 | 2 | 1 | Hi | 0 | 2016-03-26 12:05:00
3 | 1 | 3 | Are you there? I want meet you! :P | 0 | 2016-03-26 12:20:00
4 | 1 | 2 | How are you? | 0 | 2016-03-26 12:10:00
5 | 2 | 1 | Fine :) | 0 | 2016-03-26 12:15:00
6 | 5 | 1 | Hi :D | 0 | 2016-03-26 15:00:00

因此,结果应为(对于user_id == 1):

3 | 1 | 3 | Are you there? I want meet you! :P | 0 | 2016-03-26 12:20:00
5 | 2 | 1 | Fine :) | 0 | 2016-03-26 12:15:00
6 | 5 | 1 | Hi :D | 0 | 2016-03-26 15:00:00

3 个答案:

答案 0 :(得分:1)

首先按date排序,然后按user_id

分组
    SELECT *
      FROM
         (
                SELECT * from messages
                 WHERE `user_id`=1 or `recipient_id`=1
              ORDER BY `date` DESC
         ) m
  GROUP BY `user_id`

结果:

3 | 1 | 3 | Are you there? I want meet you! :P | 0 | 2016-03-26 12:20:00
5 | 2 | 1 | Fine :)                            | 0 | 2016-03-26 12:15:00
6 | 5 | 1 | Hi :D                              | 0 | 2016-03-26 15:00:00

sqlFiddle demo

答案 1 :(得分:0)

我希望我能比我的评论更好地解释,这里有:

首先,您需要拥有日志记录系统,因此当用户登录时,您将其ID保存到会话中。

第二,根据记录的用户显示他与其他用户在“收件箱”中显示的所有邮件,从邮件中选择*,其中user_id = $ _SESSION ['id'],您可以连接表并从用户和收件人显示它的名称

第三次当他点击与其他人聊天时,您会根据用户ID和recipient_id显示按日期排序的所有消息

答案 2 :(得分:0)

select * from messages group by user_id order by date这样的查询会排序吗? Fiddle演示。