select last message of conversation for each conversation in mysql

前端 未结 4 735
猫巷女王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:37

    Check this out:

    SELECT *
      FROM messages_status mst
           INNER JOIN (SELECT messages.* FROM messages INNER JOIN (
                        SELECT sender_ID,conv_id,MAX(created_at) as maxtime FROM messages
                        GROUP BY sender_ID,conv_id) as t1 ON
                        t1.sender_id = messages.sender_id AND t1.conv_id = messages.conv_id AND 
                        t1.maxtime = messages.created_at) msg 
                        ON mst.msg_id=msg.id
    WHERE mst.user_id = 1 AND mst.status NOT IN (0,3)
    ORDER BY msg.created_at DESC
    

    this is the link

    0 讨论(0)
  • 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 |
    
    0 讨论(0)
  • 2021-01-20 03:50

    As you asked get the last message of each conversation You may try this

    select *
    from messages msg
    inner join
    (
      select max(created_at) created_at
      from messages
      group by conv_id
    ) m2
      on msg.created_at = m2.created_at
    
    Inner JOIN messages_status mst ON msg.id=mst.msg_id 
    WHERE mst.user_id = 1 AND mst.status NOT IN (0,3)
    

    http://sqlfiddle.com/#!2/be010/89

    0 讨论(0)
  • 2021-01-20 03:53

    Here is the Fiddle. http://sqlfiddle.com/#!2/be010/116

    This is the query which you can use mostly:

    SELECT *
    FROM 
    (SELECT messages.id as id, 
    messages.conv_id as conv_id,
    max(messages.created_at) as created_at FROM messages,messages_status
    WHERE messages.id = messages_status.msg_id
    AND messages_status.user_id = 1 
    AND messages_status.status NOT IN (0,3)
    GROUP BY messages.conv_id) max_created
    INNER JOIN messages 
    ON messages.created_at = max_created.created_at
    INNER JOIN  messages_status mst 
    ON mst.msg_id=max_created.id
    GROUP BY messages.conv_id
    ORDER BY max_created.created_at DESC;
    
    0 讨论(0)
提交回复
热议问题