PHP板的慢mysql

我有一个 PHP板的多个表.

我需要一个有效的查询,与发布的用户选择所有类别,所有主题,主题的最后发布.使用我的查询运行它需要5-8秒.
我使用last_post_id字段对主题表进行了优化,但我需要一个更好的解决方案.

结构体

forum_categories ~ 15 lines
id|name|...

forum_topics ~ 150 lines
id|name|category_id|...

forum_posts ~ 1.000.000 lines
id|body|topic_id|user_id|...

users ~ 30.000 lines
id|username|...


category 1
 - topic 1
    - last post1 | user1
 - topic 2
    - last post2 | user2
 ...
category 2
 - topic 3
   - last post3 | user3
 ...
...

最后查询(这是我朋友的帮助.但这也很慢.)

SELECT c.NAME     AS category,t.NAME     AS topic,p.body     AS post,p.username AS username 
FROM   forum_categories AS c 
       JOIN forum_topics AS t 
         ON t.category_id = c.id 
       JOIN (SELECT * 
             FROM   (SELECT p.body,p.topic_id,u.username 
                     FROM   forum_posts AS p 
                            JOIN users AS u 
                              ON u.id = p.user_id 
                     ORDER  BY p.id DESC) AS t 
             GROUP  BY topic_id) AS p 
         ON t.id = p.topic_id

Exaplain查询

查询统计

标题是:排序,状态,时间|状态,所有时间,pct.时间,电话,时间

解决方法

我认为“主题的最后一篇文章”是您查询的关键点.这就是你在大多数内部查询中使用ORDER BY的原因,但这会产生两个子查询.

更新后的版本

CREATE TEMPORARY TABLE last_post_per_topic_t ENGINE = MEMORY
SELECT topic_id,MAX(id) AS id -----+
FROM forum_posts                    --> find last post id per topic
GROUP BY topic_id; -----------------+

ALTER TABLE last_post_per_topic_t ADD INDEX (id,topic_id);

SELECT *
FROM forum_categories AS c INNER JOIN forum_topics t ON c.id = t.category_id
INNER JOIN forum_posts p ON p.topic_id = t.id
INNER JOIN last_post_per_topic_t ON last_post_per_topic_t.topic_id = t.id
  AND last_post_per_topic_t.id = p.id;
INNER JOIN users u ON p.user_id = u.id;

第一版

SELECT *
FROM forum_categories AS c INNER JOIN forum_topics t ON c.id = t.category_id
INNER JOIN forum_posts p ON p.topic_id = t.id
INNER JOIN (
    SELECT topic_id,MAX(id) AS id -----+
    FROM forum_posts                    --- find last post_id per topic
    GROUP BY topic_id    ---------------+
) last_post_per_topic_t ON last_post_per_topic_t.topic_id = t.id
  AND last_post_per_topic_t.id = p.id;

相关文章

文章浏览阅读8.4k次,点赞8次,收藏7次。SourceCodester Onl...
文章浏览阅读3.4k次,点赞46次,收藏51次。本文为大家介绍在...
文章浏览阅读1.1k次。- php是最优秀, 最原生的模板语言, 替代...
文章浏览阅读1.1k次,点赞18次,收藏15次。整理K8s网络相关笔...
文章浏览阅读1.2k次,点赞22次,收藏19次。此网络模型提供了...
文章浏览阅读1.1k次,点赞14次,收藏19次。当我们谈论网络安...