douyingbei1458 2016-06-29 22:16
浏览 209
已采纳

从每个对话sql获取最后一条消息

I have a sql table which include conversation between users. I need to retrieve the last message from every conversation in order to preview it.

id | sender   | receiver     | message      | date
 1 |        1 |            2 | Hello        | 2015-12-08 20:00
 2 |        2 |            1 | Hey          | 2015-12-08 20:10
 3 |        2 |            1 | You there?   | 2015-12-08 21:00
 4 |        1 |            3 | Yes          | 2015-12-08 21:15
 5 |        4 |            1 | Hey buddy    | 2015-12-08 22:00

I know many similar question on site but i couldn't fix this.

I tried this code but not working properly:

SELECT *
FROM   messages
WHERE  receiver = '{$id}'
GROUP BY sender
ORDER BY id DESC
LIMIT 10;
  • 写回答

4条回答 默认 最新

  • doutou7740 2016-06-29 22:50
    关注

    Just to define what is a conversation in your table is a pain, i suppose a conversation is all the rows where

    (sender=@senderId && receiver=@receiverId) || (sender=@receiverId && receiver=@senderId)

    Group by this concept, i don't even want to think it

    For me you are missing a concept, the "conversation"

    If you have a table conversation like this

    ConversationId |  Users1  |  User2
    

    And Message like

    Id | ConversationId | UserSendingId | Message | Date
    

    Now you can Group by ConversationId and take the last message like

    SELECT *  <-- avoid * better use all row names
    FROM Message 
    Where id in (
     select max(id) from message group by ConversationId
    )
    

    The representation of the conversation table is just a fast approach you can do a better solution with a relation from 1 to many of conversation and users in conversation to avoid modified conversation table when you want to have more than 2 users per conversation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测