douruduan8812 2012-06-03 12:23
浏览 34
已采纳

MySQL优化 - 删除某些计数

I'm building a chat for a turn-based game (using PHP and MySQL) where I only want to save the 30 most recent messages in the MySQL database.

Currently, I'm doing 3 queries to delete the oldest message when the count exceeds 30:

  1. Insert the new chat message as a new row:

    INSERT INTO chatMessages (userId,matchId,message,timestamp) VALUES (".$params["userId"].",".$params["matchId"].",'".$params["message"]."',NOW())

  2. Check if there are too many messages in the database, and get the oldest one's Id.

    SELECT COUNT(id) AS count, id AS oldestId FROM chatMessages WHERE matchId = ".$params["matchId"]." ORDER BY id ASC LIMIT 1

  3. Remove the oldest message

    DELETE FROM chatMessages WHERE id = ".$oldestId

Is there any way to do this in 2, or even 1 single query? We have quite a lot of traffic on our servers, so performance is key.

  • 写回答

1条回答 默认 最新

  • doubu4826 2012-06-03 12:25
    关注

    You can reduce the 2nd and 3rd query to one:

    delete from chatMessages 
    where id not in (select id from chatMessages 
                     order by id desc 
                     limit 30)
    

    You could put that in an insert trigger. That way oldest records would get deleted automatically after an insert.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程