Is there a simpler way to achieve this style of user messaging?

前端 未结 13 1302
轮回少年
轮回少年 2020-12-24 12:20

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,

13条回答
  •  青春惊慌失措
    2020-12-24 13:08

    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
    

提交回复
热议问题