Query returns additional rows

后端 未结 4 1130
无人及你
无人及你 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:27

    You are getting the last message from each user because you have done GROUP BY for both: to_user and from_user.

    There is no need to use GROUP BY clause in your query.

    0 讨论(0)
  • 2021-01-20 16:30

    Remove the group by clause in your in statement--it's useless in this case. It's returning a sent timestamp for each distinct pairing of to_user and from_user. You really just want the max sent where to_user or from_user equal some value. Lose the group by, and you'll return exactly one record showing the latest message either to or from a user.

    It looks like this:

    SELECT *
    FROM `messages`
    WHERE `sent`
    IN (
       SELECT MAX( `sent` )
       FROM `messages`
       WHERE `from_user` = '1' --id of user who is requesting the list
       OR `to_user` = '1'  --id of user who is requesting the list
       )
    LIMIT 0 , 30
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-20 16:41
    SELECT *
    FROM `messages`
    WHERE `sent`
    IN (
       SELECT MAX( `sent` )
       FROM `messages`
       WHERE (`from_user` = '1' OR `to_user` = '1')
       )
    LIMIT 0 , 30
    

    the groupby is going to conbine them i believe.

    0 讨论(0)
提交回复
热议问题