I have created a messaging system for users, it allows them to send a message to another user. If it is the first time they have spoken then a new conversation is initiated,
If you want to simplify your query you should add the last message id in your table userconversation :
ALTER TABLE userconversation ADD lastusermessageid
then each time you add a new message you should update your table userconversation :
INSERT INTO userconversation(userId, friendId, lastusermessageid)
VALUES (:userId, :friendId, :lastusermessageid)
ON DUPLICATE KEY UPDATE lastusermessageid = VALUES(lastusermessageid)
and finally add indexes on all foreign keys :
SELECT
c.id,
c.userId,
c.friendId,
m.message,
m.read,
UNIX_TIMESTAMP(m.time),
user1.username,
user2.username
FROM
userconversation c
INNER JOIN usermessages m ON c.lastusermessageid = m.id
INNER JOIN user user1 ON c.userId = user.id
INNER JOIN user user2 ON c.friendId = user.id
WHERE
c.userId = :userId OR c.friendId = :userId
ORDER BY
m.id DESC
LIMIT 10