select last message of conversation for each conversation in mysql

前端 未结 4 734
猫巷女王i
猫巷女王i 2021-01-20 03:10

my query:

SELECT *
  FROM messages_status mst
       INNER JOIN messages msg 
             ON mst.msg_id=msg.id
 WHERE mst.user_id = 1 
       AND mst.status         


        
4条回答
  •  孤街浪徒
    2021-01-20 03:43

    SQLFIDDLEExample

    Query:

    SELECT msg.*
    FROM messages_status mst
    INNER JOIN messages msg ON mst.msg_id=msg.id
    LEFT JOIN messages ms2
     ON ms2.conv_id = msg.conv_id
     AND ms2.created_at > msg.created_at
    WHERE mst.user_id = 1 
     AND mst.status NOT IN (0,3)
     AND ms2.created_at is null
    

    Result:

    | ID | SENDER_ID | CONV_ID |       CONTENT |                   CREATED_AT |                   UPDATED_AT |
    |----|-----------|---------|---------------|------------------------------|------------------------------|
    | 16 |         3 |       3 |         hy :) | March, 26 2014 16:38:17+0000 | March, 26 2014 16:38:17+0000 |
    | 14 |         1 |       1 | kjhkjhkjh  kl | March, 26 2014 16:16:25+0000 | March, 26 2014 16:16:25+0000 |
    

提交回复
热议问题