SQL - 改进JOIN查询(需要很长时间才能加载)

时间:2015-10-22 21:17:29

标签: php mysql sql join pdo

我有下面的查询,我相信我已经尽可能地进行了优化:

.minus

这是每个论坛的统计数据:

SELECT 
        c.forum_id as category_id,
        c.forum_name as category_name,
        t.forum_id as id,
        t.forum_name as name,
        t.forum_desc as description,
        (SELECT COUNT(*) FROM forum_topics WHERE forum_id=t.forum_id AND topic_deleted=0) as topics_count,
        (SELECT COUNT(*) FROM forum_posts WHERE forum_id=t.forum_id AND post_deleted=0) as posts_count,
        (SELECT COUNT(*) FROM forum_posts WHERE topic_id=lp.topic_id AND post_deleted=0) as last_post_count,
        lp.topic_id as last_post_topic_id,
        lp.topic_title as last_post_topic_title,
        lp.post_time as last_post_time,
        lp.username as last_post_username,
        lp.avatar
    FROM forum_cats as t
    JOIN forum_cats as c on c.forum_id = t.forum_type_id
    left join (
        SELECT 
            ft.topic_id,
            ft.title as topic_title,
            tmp.post_time,
            u.username,
            u.avatar,
            fp.forum_id
        FROM
            forum_posts fp
            join forum_topics ft on ft.topic_id = fp.topic_id
            join users u on u.id = fp.userid
            join (
                select forum_id, max(`post_time`) `post_time`
                from forum_posts fp
                where fp.post_deleted = 0
                group by forum_id
                ) as tmp on (fp.forum_id = tmp.forum_id and fp.post_time = tmp.post_time)
        where post_deleted = 0 and ft.topic_deleted = 0
    ) as lp on lp.forum_id = t.forum_id
    where t.forum_active = 1 and c.forum_active = 1
    order by category_id, t.forum_id

我在上述查询中选择的所有列上添加了 forum_cats has 20 rows forum_topics has 900 rows forum_posts has 9000 rows users has 18000 rows 。但执行此操作仍需要2秒多的时间。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

不会topics_countposts_count&每一行last_post_count都一样吗?分别提取这些值是不是更有效率,而不是为你拉动的每一行进行相同的3次计算?