I have created 2 table messages and Conversation.
Conversation table will create an unique id for two users who is sending and receiving messages.
Messages table will contains all info of user messages.
Conversation table
conversation_id | user_id1 | user_id2 |last_message_id
1 5 1 4
2 5 2 5
message_id | conversation_id | sender_id | message | created_time
1 1 5 MSG A 2012-06-10 00:20:04
2 1 5 MSG B 2012-06-10 00:20:21
3 1 5 MSG C 2012-06-10 00:21:09
4 1 1 MSG D 2012-06-10 00:22:23
5 2 5 MSG E 2012-06-10 00:25:16
Output I want:
sender_id | message | created_time
5 MSG E 2012-06-10 00:25:16
1 MSG D 2012-06-10 00:22:23
What I tried:
SELECT * FROM conversation c, messages m
WHERE c.user_id1='$userid' OR c.user_id2='$userid'
AND c.last_message_id=m.message_id
ORDER BY created_time DESC
But this query is not displaying right result.
Do we need something like following to group by as well?
SELECT * FROM TABLE
WHERE CONDITION
(SELECT MAX(created_time)
FROM TABLE
GROUP BY SOMEFEILD)
order by time desc
Try to change your query like this