I have this SQL table Messages
where the relevant entries are sender
, recipient
, timestamp
and text
. So for instance some examples would be
sender recipient text timestamp
user1 user2 hey 1
user2 user1 hello back 2
user1 user3 hey other dude 3
And in order to populate a view like in iMessage
for instance; I need an SQL query that for a given user gets the most recent message in each conversation that user is having. So currently what I have is
SELECT *
FROM Messages m
WHERE m.timestamp IN (SELECT MAX(m2.timestamp)
FROM Messages m2
WHERE m.sender = :user OR m.recipient = :user
GROUP BY sender, recipient)
But unfortunately this query returns all 3 of the messages above because the nested select groups the first two separately even though they're both in the same conversation. Is there a simple way to express what I really want in SQL, preferably without creating a Conversations table and doing some sort of joiny business?