简体   繁体   中英

Speed up SQL query with multiple joins

I have a query that takes about 4 minutes to run. Is there any way I can optimize this query? I am using 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.

 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:

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. if you want to have aggregation, add all non-aggregation columns to group by and use atleast one aggregation function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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