我有一个从六个表中获取数据的查询,但是获取数据需要花费太多时间。浏览器加载并显示有时没有任何结果。当我在MySQL数据库中运行此查询时,需要很长时间才能执行。
SELECT SQL_CALC_FOUND_ROWS movies.*,
curriculums.name AS curriculum,
teachers.name AS teacher,
movie_sub_categories.name AS sub_cat_name,
movie_categories.name AS cat_name
FROM movies
LEFT JOIN curriculums on movies.curriculum_id = curriculums.id
LEFT JOIN teachers on movies.teacher_id = teachers.id
LEFT JOIN movies_movie_sub_categories on movies.id = movies_movie_sub_categories.movie_id
LEFT JOIN movie_sub_categories on movies_movie_sub_categories.movie_sub_category_id = movie_sub_categories.id
LEFT JOIN movie_categories on movie_sub_categories.movie_category_id = movie_categories.id
ORDER BY id LIMIT 0, 50
答案 0 :(得分:1)
表movies_movie_sub_categories需要有一个关于movie_id的索引和一个关于movie_sub_category_id的单独索引。如果没有这两个索引,查询构建器将被强制扫描每个记录两次(因为查询有两个单独的连接子句引用该表)
答案 1 :(得分:1)
这不是一个非常令人兴奋的查询 - 它只是提供了id
所属的表的前50行。当JOINing
时,请对列进行限定,以便我们知道发生了什么。
你真的需要LEFT
吗?
假设您需要LEFT
且id
属于movies
,那么这应该会更快地运行:
同时,在movies
中只查找一次有多少行,这样您就不必每次都计算它。
SELECT movies.*, curriculums.name AS curriculum,
teachers.name AS teacher, movie_sub_categories.name AS sub_cat_name,
movie_categories.name AS cat_name
FROM ( SELECT id FROM movies ORDER BY id LIMIT 0, 50 ) AS m
JOIN movies USING(id)
LEFT JOIN curriculums AS c ON movies.curriculum_id = c.id
LEFT JOIN teachers AS t ON movies.teacher_id = t.id
LEFT JOIN movies_movie_sub_categories AS mmsc ON movies.id = mmsc.movie_id
LEFT JOIN movie_sub_categories AS msc ON mmsc.movie_sub_category_id = msc.id
LEFT JOIN movie_categories AS mc ON msc.movie_category_id = mc.id
ORDER BY m.id
请使用SHOW CREATE TABLE
;我们需要看看你是否有足够的索引,比如
mmsc: INDEX(movie_id)