dsdqpdjpq16640651 2015-10-22 21:17
浏览 126
已采纳

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

I have below query, which I believe I have optimized as much as I possible could:

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

This is the stats for each forum:

    forum_cats has 20 rows
    forum_topics has 900 rows
    forum_posts has 9000 rows
    users has 18000 rows

I have added index on all the columns that is being selected in above query. Yet it still takes more than 2 seconds to execute this.

What am I missing here?

  • 写回答

1条回答 默认 最新

  • doukai1226 2015-10-22 21:23
    关注

    Won't topics_count, posts_count & last_post_count be the same for every row? Wouldn't it be more efficient to pull these values separately, rather than make the same 3 calculations for every row you pull?

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

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)