Are you tracking what Message ID each message is in reply to?
If not, you'll probably need something along these lines:
conversation(
convoID,
replyTo,
messageID
)
When a user sends a new message, create a new row.
This row should contain (a new convoID, null replyTo, and the id of the message)
When a user replies to a message, use the convoID from the replying message.
This way your data looks like this:
(user1/2 and user3/4 are conversing)
messages:
1, user1, 'yo'
2, user2,' hey'
3, user1, 'whats up?'
4, user2, 'not much'
5, user3, 'I need help'
6, user4, 'too bad'
conversations:
1, null, 1 // first conversation, not a reply, message1
1, 1, 2 // first convo, replying to message1, message2
1, 2, 3 // first convo, replying to message2, message3
1, 3, 4 // first convo, replying to message3, message4
2, null, 5 // 2nd convo, not a reply, message5
2, 5, 6 // 2nd convo, replying to message5, message6
Find convoID of the message "SELECT * FROM convos WHERE replyID = $messageID"
Find last convoID = "SELECT convoID FROM convos ORDER BY convoID DESC LIMIT 1"
get list of messageIDs in a convo =
"SELECT * FROM convos, messages
INNER JOIN messages
ON convos.messageid = messages.messageid
WHERE convoID = $id"