mySQL Group by member name

前端 未结 1 1659
后悔当初
后悔当初 2021-01-29 15:20

I am using this query to fetch list of who messaged a user or who user messaged to.

SELECT messages.* 
FROM (
    SELECT MAX(lastseen) AS lastseen 
    FROM mess         


        
相关标签:
1条回答
  • 2021-01-29 15:26

    I think this is what you're after.

    SELECT messages.* 
      FROM 
      (SELECT MAX(lastseen) AS lastseen,IF ('Tom' = `from`,`to`,`from`) as otheruser FROM messages
        WHERE 'Tom' IN (`from`,`to`) GROUP BY otheruser
       )
    AS latest INNER JOIN messages ON latest.lastseen = messages.lastseen
                                 AND (('Tom' = messages.from AND latest.otheruser = messages.to)
                                     OR
                                     ('Tom' = messages.to AND latest.otheruser = messages.from))
    ORDER BY messages.lastseen
    DESC,`read`='no' limit 10
    

    just replace 'Tom' with your variable

    This will return the latest 10 users that messaged to 'Tom' or 'Tom' messaged to.

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