我有一个带有一些n:m关系表的数据库,我正在使用一个非常大的查询来组合所有这些表。我们先来看看我的数据库:
我创建了两个视图来比较性能。
第一视图:
CREATE VIEW `band_page1` AS (
SELECT maid, band_name, band_logo, band_img,
(SELECT countries.country_name from countries WHERE band_info.id_country = countries.id) as country,
(SELECT locations.location_name from locations WHERE band_info.id_location = locations.id) as location,
(SELECT status.status_name from status WHERE band_info.id_status = status.id) as status,
(SELECT founding.fyear from founding WHERE band_info.id_founding = founding.id) as founding,
(SELECT active.ayear from active WHERE band_info.id_active = active.id) as active,
(SELECT GROUP_CONCAT(DISTINCT genres.genre_name ORDER BY genres.genre_name)
FROM genres LEFT JOIN band_genres ON band_genres.id_genre = genres.id
WHERE band_genres.id_band = band_info.maid) AS genre,
(SELECT GROUP_CONCAT(DISTINCT themes.theme_name ORDER BY themes.theme_name)
FROM themes LEFT JOIN band_themes ON band_themes.id_theme = themes.id
WHERE band_themes.id_band = band_info.maid) AS themes,
(SELECT GROUP_CONCAT(DISTINCT labels.label_name ORDER BY labels.label_name)
FROM labels LEFT JOIN band_labels ON band_labels.id_label = labels.id
WHERE band_labels.id_band = band_info.maid) AS label
FROM band_info
GROUP BY band_info.maid);
第二视图:
CREATE VIEW `band_page2` AS (
SELECT band_info.maid, band_info.band_name, band_info.band_logo, band_info.band_img,
(SELECT countries.country_name from countries WHERE band_info.id_country = countries.id) as country,
(SELECT locations.location_name from locations WHERE band_info.id_location = locations.id) as location,
(SELECT status.status_name from status WHERE band_info.id_status = status.id) as status,
(SELECT founding.fyear from founding WHERE band_info.id_founding = founding.id) as founding,
(SELECT active.ayear from active WHERE band_info.id_active = active.id) as active,
GROUP_CONCAT(DISTINCT genres.genre_name ORDER BY genres.genre_name) AS genre,
GROUP_CONCAT(DISTINCT themes.theme_name ORDER BY themes.theme_name) AS themes,
GROUP_CONCAT(DISTINCT labels.label_name ORDER BY labels.label_name) AS label
FROM band_info
LEFT JOIN band_genres ON band_genres.id_band = band_info.maid
LEFT JOIN band_themes ON band_themes.id_band = band_info.maid
LEFT JOIN band_labels ON band_labels.id_band = band_info.maid
LEFT JOIN genres ON genres.id = band_genres.id_genre
LEFT JOIN themes ON themes.id = band_themes.id_theme
LEFT JOIN labels ON labels.id = band_labels.id_label
GROUP BY band_info.maid);
当我转到phpmyadmin并打开一个视图时,两个视图都需要3秒才能显示查询结果。我正在使用此视图进行如下查询:
SELECT * FROM band_page1 where maid = '$id';
使用php感觉好像花了很长时间才能得到结果。 它不仅耗时3秒,还需要更长的时间。 我的问题是,我如何优化我的查询?
答案 0 :(得分:1)
有过这样的事情:"过度规范化"。
有标准的"国家/地区代码"这是2个字母。将它们INT
而不是YEAR
设置为另一个表格。这将该列从4个字节减少到2个。并且删除了查找。
status
是一个2字节的数据类型;不要把这种情况正常化。
考虑将ENUM
转换为1字节VIEWs
而不是查找。
可能还有其他人。
GROUP BY
是语法糖,从不提高性能。有时表现会更差。
我认为首先 VIEW
中的band_*
没有任何用处。
{{1}}表似乎是多对多映射表。遵循these tips可以提高他们的表现。