mysql-如何提高从SQL的提取速度?
作者:互联网
我不是MySQL索引方面的专家,但是我看到了很多教程,但是使用PHP加载页面仍然需要7秒钟.
我在MySQL表中大约有5万行和30列.
如何提高MySQL Fetching数据速度?我可以在下面的查询中进行任何改进吗?
SELECT tmdb_movies.movie_title,tmdb_movies.budget,tmdb_movies.original_language,tmdb_movies.original_title
,translations.translations_english_name
,videos.videos_name,videos.videos_key
FROM tmdb_movies
LEFT JOIN
(
SELECT
translations_tmdb_id
,GROUP_CONCAT(DISTINCT translations.translations_english_name SEPARATOR ', ') AS translations_english_name
FROM translations
GROUP BY translations_tmdb_id
) translations ON translations.translations_tmdb_id = tmdb_movies.tmdb_id
LEFT JOIN
(
SELECT
videos_tmdb_id
,GROUP_CONCAT(DISTINCT videos.videos_name) as videos_name
,GROUP_CONCAT(DISTINCT videos.videos_key) as videos_key
FROM videos
GROUP BY videos_tmdb_id
) videos ON videos.videos_tmdb_id = tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id= '$tmdb_id'
在这里,我使用tmdb_id连接所有表.在MySQL中为tmdb_id,translations_tmdb_id和videos_tmdb_id编制了索引.
这是我的MySQL表结构的示例:
tmdb_movies表:
tmdb_id movie_title
1 Logan
2 Iron Man
3 Superman
翻译表
translations_tmdb_id translations_english_name
1 English
1 Hindi
1 French
2 English
2 Spanish
2 Hindi
视频表
videos_tmdb_id videos_name
1 Official Trailer
1 Trailer 2
2 Trailer 1
2 Trailer 2 HD
3 Superman Trailer 1
3 Superman Trailer 2
解决方法:
>为什么使用GROUP_CONCAT(DISTINCT …)?没有重复项.
>您仅选择一部电影的数据.但是您的派生表可以读取并汇总所有电影.出色的优化器会仔细检查该内容,并仅汇总该部电影的记录.如果这是甲骨文,我完全可以这样.但是使用MySQL吗?我不会依靠这个.因此,在您的子查询中添加一个where子句.
>如果没有order by子句,则不应选择视频名称和键.对它们进行排序,以使它们具有相同的顺序,即,名字与第一个键匹配等等.
这是您的查询重写:
SELECT
m.movie_title,
m.budget,
m.original_language,
m.original_title,
t.translations_english_names,
v.videos_names,
v.videos_keys
FROM tmdb_movies m
CROSS JOIN
(
SELECT
GROUP_CONCAT(translations_english_name SEPARATOR ', ') AS translations_english_names
FROM translations
WHERE translations_tmdb_id = @tmdb_id
) t
CROSS JOIN
(
SELECT
GROUP_CONCAT(videos_name ORDER BY videos_name) as videos_names,
GROUP_CONCAT(videos_key ORDER BY videos_name) as videos_keys
FROM videos
WHERE videos_tmdb_id = @tmdb_id
) v
WHERE m.tmdb_id = @tmdb_id;
这些是您应该使用的索引:
create index idxm on tmdb_movies(tmdb_id); -- if tmdb_id is PK, you have this already
create index idxt on translations(translations_tmdb_id, translations_english_name);
create index idxv on videos(videos_tmdb_id, videos_name, videos_key);
标签:query-performance,aggregate-functions,mysql 来源: https://codeday.me/bug/20191025/1931941.html