【问题标题】:SQL - Improving JOIN query (Taking long time to load)SQL - 改进 JOIN 查询(​​加载时间长)
【发布时间】:2016-01-22 07:34:50
【问题描述】:

我有以下查询,我相信我已尽可能优化:

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

我已在上述查询中选择的所有列上添加了index。然而,执行此操作仍然需要 2 秒以上。

我在这里错过了什么?

【问题讨论】:

  • 删除这两个子连接并将它们变成一个临时表。这应该会加快你的速度。
  • 嘿!你介意举个例子吗?谢谢!
  • 这种没有EXPLAIN输出的问题是没有意义的
  • @oliverbj 更新您的问题,以便清楚地理解问题,用示例数据显示您的 4 个表格并显示其中的预期数据,然后我们可以为您提供帮助。

标签: php mysql sql join pdo


【解决方案1】:

topics_countposts_countlast_post_count 不会对每一行都相同吗?单独提取这些值不是更有效,而不是为您提取的每一行进行相同的 3 次计算吗?

【讨论】:

  • 非常感谢您的回答。你介意用它的样子更新它吗?对不起,但这是我能想到的唯一方法。对新的眼睛总是有帮助的 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 2014-07-07
  • 2016-06-25
  • 1970-01-01
相关资源
最近更新 更多