简体   繁体   English

通过多个联接加快SQL查询

[英]Speed up SQL query with multiple joins

I have a query that takes about 4 minutes to run. 我有一个查询,大约需要4分钟才能运行。 Is there any way I can optimize this query? 有什么方法可以优化此查询? I am using MySQL 5.6.20 . 我正在使用MySQL 5.6.20。 I have tried adding the AND clauses of each inner join to be a subquery for the last WHERE clause, but it had no effect. 我尝试将每个内部联接的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

I've used explain select to find indexes, but i'm not sure what to modify at this point: 我已经使用了explain select来查找索引,但是目前还不确定要修改什么:

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

first and foremost thing is make sure you have proper indexes on the tables which are being used in the query. 首先也是要确保在查询中使用的表上具有正确的索引。

secondly follow the order of joins from small table to larger one in a sequence, so the result data get narrowed. 其次,按照顺序从小表到大表的连接顺序,使结果数据变窄。

other thing I noticed is the query given here won't run properly as group by just has one columns where select clause have various columns, more over I did not see use of group by here as there is no aggregation. 我注意到的另一件事是,这里给出的查询不能作为group by正常运行,因为只有一列,其中select子句具有各种列,而且我没有看到group by的使用,因为这里没有聚合。 if you want to have aggregation, add all non-aggregation columns to group by and use atleast one aggregation function. 如果要进行聚合,请添加所有非聚合列进行分组,并使用至少一个聚合函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM