使用多个连接加速SQL查询

时间:2014-11-17 22:46:17

标签: mysql

我有一个大约需要4分钟才能运行的查询。有什么办法可以优化这个查询吗?我正在使用MySQL 5.6.20。我已经尝试将每个内连接的AND子句添加为最后一个WHERE子句的子查询,但它没有效果。

 SELECT h.userId 
     , h.pageId 
     , h.id 
     , h.content highlightContent
     , h.createdAt highlightCreatedAt
     , h.tagName
     , h.inputId
     , h.children 
     , p.topic_title pageTitle
     , p.topic_uuid guid
     , p.topic_position pagePosition
     , p.lcms_module_uuid pageModuleId
     , mp.module_position modulePosition
     , mp.lcms_module_uuid moduleID
     , mp.section_uuid moduleSectionUUID
     , mp.module_title moduleTitle
     , sp.section_uuid sectionGuid
     , sp.section_position sectionParentId
     , sp.album_uuid sectionAlbumID
     , sp.section_title albumTitle
     , ap.album_title albumPath
     , ap.album_uuid
     , ap.id albumId
     , ps.id publishId
  FROM highlights h
  JOIN LCMS3.topic_publishes p
    ON p.topic_uuid = h.pageId
   AND p.publish_schema_id = 5784
  JOIN LCMS3.lcms_module_publishes mp 
    ON p.lcms_module_uuid = mp.lcms_module_uuid
   AND mp.publish_schema_id = 5784 
  JOIN LCMS3.section_publishes sp 
    ON sp.section_uuid = mp.section_uuid
   AND sp.publish_schema_id = 5784
  JOIN LCMS3.album_publishes ap 
    ON ap.album_uuid = sp.album_uuid
   AND ap.publish_schema_id = 5784
  JOIN LCMS3.publish_schemas ps 
    ON ps.topic_publish_uuid = p.topic_publish_uuid
 WHERE h.userId = '364663286b6de43c21d7dafe29370441' 
   AND p.album_uuid = '49152e6b-ca80-4889-a65e-4e6fd1dcc367' 
 GROUP 
    BY h.id
 ORDER 
    BY albumId
     , sectionParentId
     , modulePosition
     , pagePosition

我已经使用explain select来查找索引,但我不确定此时要修改什么:

http://i61.tinypic.com/33tksw2.png

1 个答案:

答案 0 :(得分:0)

首先要确保在查询中使用的表上有适当的索引。

其次遵循序列中从小表到较大表的连接顺序,因此结果数据变窄。

我注意到的另一件事是这里给出的查询不能正确地作为组运行,只有一列其中select子句有各种列,更多我没有看到使用group by here,因为没有聚合。如果要进行聚合,请将所有非聚合列添加到分组依据,并使用至少一个聚合函数。

相关问题