Query returns additional rows

后端 未结 4 1132
无人及你
无人及你 2021-01-20 15:49

I have this kind of table for simple chat:

messages table structure
+----+---------+-----------+---------+------+------+
| id | to_user | from_user | message         


        
4条回答
  •  情歌与酒
    2021-01-20 16:38

    Here's how you do it:

    SELECT *
    FROM (SELECT * 
      FROM messages
      WHERE from_user = ?
      OR to_user = ?
      ORDER by from_user, to_user, sent DESC
    ) x
    GROUP BY from_user, to_user
    ORDER BY sent DESC
    LIMIT 1;
    

    In mysql, a group by without aggregating the other columns returns the first row for each group. By selecting form an ordered row set (the inner query) we get the most recent row for each conversation.

提交回复
热议问题