I have created a messaging system for users which will allow users to send message to another.
For this I have created two tables.
conversation(conversation_id,user_id1,user_id2)
messages(message_id,conversation_id,sender_id,receiver_id,message,created_time)
If users are talking first time, a conversation_id will be created with user_id1(who initiate chat) and user_id2(to who user_id1 is sending message)
Messages table will contain all info related to message.
Now what I want is, to create a message summary page where logged in user can view his all conversation list between other users order by created_time, group by conversation_id.
Here are table data:
conversation_id | user_id1 | user_id2
1 100 103
2 101 103
3 103 102
message_id| conversation_id| sender_id| receiver_id| message | created_time
1 1 100 103 MSG A 2012-06-08 08:38:57
2 1 103 100 MSG B 2012-06-08 08:39:40
3 2 101 103 MSG C 2012-06-08 08:40:20
4 3 102 103 MSG D 2012-06-08 08:41:10
And here is what output what I am looking for: Lets say logged in user is with id: 103
conversation_id| conversation_with | last_message | created_time
3 102 MSG D 2012-06-08 08:41:10
2 101 MSG C 2012-06-08 08:40:20
1 100 MSG B 2012-06-08 08:39:40
So this output is ordering by created_time, Grouping by conversation_id and displaying id of user in conversation_with , with who userid 103 is having conversation.
Can somebody provide MySQL query I will need to get this output.
This was a fun one. So, you have three main things to solve.
conversation_withcolumn depending on where the desired user shows up amongst two columns.greatest-n-per-groupto find the most recentmessage.least-n-per-groupto find the earliest messagecreated_time.The first one I solved by querying twice, alternating the
user_idcolumn, unioning the results, and then ordering the unioned results bycreated_time. I think I can solve this with one query and no unions, but it works for now.2 and 3 are a little more involved. Here’s a SQL fiddle with the query: http://sqlfiddle.com/#!2/bf2b7/1
TL;DNR