select last message of conversation for each conversation in mysql

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

提交回复
热议问题