加入慢查询

时间:2013-10-14 10:51:10

标签: mysql join

请优化此查询。我想要实现的是加入大约8个表,其中只有大约3个表包含大数据(1.5m记录)。此查询返回预期的记录,但运行1分钟是坏的。 我知道它可以进行优化以更好地执行,请您需要专家的帮助。我已经在用于连接的字段上有索引。

SELECT topic_id, 
   topic_title, 
   unit_name_abbrev, 
   sch_name_abbrev, 
   picture_small_url    AS thumbnail, 
   profile_pix_upload_path, 
   first_name, 
   last_name, 
   topic_poster, 
   topic_replies, 
   topic_views, 
   topic_last_post_time AS topic_post_time, 
   sch_sub_forum_id 
FROM   (_sch_forum_topics 
    INNER JOIN _users 
            ON ( _users.userid = _sch_forum_topics.topic_poster ) 
    INNER JOIN _profile 
            ON _profile.userid = _users.userid 
    INNER JOIN _class 
            ON _users.classid = _class.classid 
    INNER JOIN _level 
            ON _class.level_id = _level.id 
    INNER JOIN _unit 
            ON _class.unitid = _unit.unitid 
    INNER JOIN _department 
            ON _unit.deptid = _department.deptid 
    INNER JOIN _faculty 
            ON _department.facid = _faculty.facid 
    INNER JOIN _university 
            ON _faculty.schid = _university.schid) 
WHERE  _sch_forum_topics.sch_sub_forum_id = 4 
ORDER  BY _sch_forum_topics.topic_last_post_time DESC 
LIMIT  0, 15 

1 个答案:

答案 0 :(得分:0)

尝试在制作JOIN之前进行过滤。

SELECT topic_id, 
   topic_title, 
   unit_name_abbrev, 
   sch_name_abbrev, 
   picture_small_url    AS thumbnail, 
   profile_pix_upload_path, 
   first_name, 
   last_name, 
   topic_poster, 
   topic_replies, 
   topic_views, 
   topic_last_post_time AS topic_post_time, 
   sch_sub_forum_id
FROM
 ( select  * FROM  sch_forum_topics WHERE sch_sub_forum_id = 4
ORDER BY topic_last_post_time DESC 
LIMIT  0, 15 ) main
    INNER JOIN _users 
            ON ( _users.userid = main.topic_poster ) 
    INNER JOIN _profile 
            ON _profile.userid = _users.userid 
    INNER JOIN _class 
            ON _users.classid = _class.classid 
    INNER JOIN _level 
            ON _class.level_id = _level.id 
    INNER JOIN _unit 
            ON _class.unitid = _unit.unitid 
    INNER JOIN _department 
            ON _unit.deptid = _department.deptid 
    INNER JOIN _faculty 
            ON _department.facid = _faculty.facid 
    INNER JOIN _university 
            ON _faculty.schid = _university.schid);