Ok, I'm trying to base something similar off of this, but not quite getting it nailed: [GROUP BY and ORDER BY](https://stackoverflow.com/questions/4119576/group-by-and-order-by/6471137)

Basically, wanting a query to find the latest messages in each 'thread' between the current logged-in user and any other users, but via a flat (non-'threaded') table of messages:

```
messages {
  id,
  from_uid,
  to_uid,
  message_text,
  time_added
}

```

Assuming the current user's uid is '1', and the latest message in each 'thread' could either be *from* that user, or *to* that user (the other party always denoted by thread\_recipient):

```
SELECT a.*,thread_recipient
  FROM messages a
  JOIN (SELECT IF(from_uid = '1',to_uid,from_uid) AS thread_recipient,
               MAX(time_added) AS recency
          FROM messages 
         WHERE (from_uid = '1' OR to_uid = '1')
      GROUP BY thread_recipient) b ON thread_recipient = (IF(a.from_uid = '1',a.to_uid,a.from_uid))
                             AND b.recency = a.time_added
 ORDER BY a.time_added DESC

```

But I fear this ain't gonna work right, and maybe messages sent at the same time might end up being returned for the wrong user?

Is my WHERE condition misplaced?

Any wisdom much appreciated.