Query returns additional rows

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

提交回复
热议问题