I have a messages table
messages
--------------
user_id_from (int)
user_id_to (int)
text (varchar)
date (datetime)
isRead (boolean)
I want to get messages activity for user where inbox and outbox are in one list (same as facebook messages). I want to get the last message for each user I contact. I tried to do this:
lets say this is my data
user_id_from user_id_to text date isRead
100 101 "text1" 2011/1/1 0
101 100 "text2" 2011/1/2 0
100 102 "text3" 2011/1/5 0
Here’s my query:
select *
from Message m
where m.user_id_to = 100
or m.id in
(select m2.id
from Message m2
where m2.user_id_from = 100
and m2.user_id_to != m.user_id_from
)
group by m.user_id_from, m.user_id_to
This query gives me the complete messages where user 100 is there.
How can I do this?
This would require you to keep track of ‘threads’ in messages, or you could also call them conversations. Every time you send a message, it gets a conversation_id. Then, you make a table of user_conversation_subscriptions. Sending a message to someone starts a new conversation, with the sender and receiver as the only participants, but they could invite people into the conversation. Than, you could get the new messages grouped by conversation to see in which conversation you’ve got new messages, that’s how it works on facebook.