我应该为这个慢速多连接查询添加哪些索引?

时间:2013-10-11 19:14:13

标签: mysql sql join left-join database-indexes

我需要找到能说一种特定语言并且在将来可用的有效位置的老师或教师的主要位置,而无需显示可用性。多名教师可以在同一地点。此查询有效,但速度很慢。我应该使用哪些索引?

Select
  teachers.teacher_id, 
  teacherLocations.location_id
From
  tdb_teachers AS teachers
Join 
  tdb_teacher_languages As teacherLanguages
    On teacherLanguages.teacher_id = teachers.teacher_id And
       teacherLanguages.language_id = 33
Left Join
  tdb_availability As locAvail
    On locAvail.teacher_id = teachers.teacher_id And
       locAvail.end_date >= 1381449600
Join
  tdb_locations AS teacherLocations
    On (
      teacherLocations.location_id = locAvail.location_id Or
      teacherLocations.location_id = teachers.location_id
   ) And
   teacherLocations.latitude != "" And
   teacherLocations.longitude != ""

1 个答案:

答案 0 :(得分:1)

首先尝试这是否会给你带来更好的结果:

Select
  teachers.teacher_id, 
  teacherLocations.location_id
From
  tdb_teachers AS teachers
Join 
  tdb_teacher_languages As teacherLanguages
    On teacherLanguages.teacher_id = teachers.teacher_id 
Left Join
  tdb_availability As locAvail
    On locAvail.teacher_id = teachers.teacher_id And
Join
  tdb_locations AS teacherLocations
    On (
      teacherLocations.location_id = locAvail.location_id Or
      teacherLocations.location_id = teachers.location_id
   ) 
WHERE
   teacherLocations.latitude != "" 
   And teacherLocations.longitude != ""
   AND locAvail.end_date >= 1381449600
   And teacherLanguages.language_id = 33

然后在非空字段上添加索引,看起来像tdb_teacher_languages.end_date和tdb_teacher_languages.language_id是您最好的候选者。 之后你可以试着在这里粘贴解释计划。