<?php
$db = new mysqli(//editted out db credentials);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT m.ID, m.Title, GROUP_CONCAT(a.Title) AS Artist
FROM mp3s m
LEFT JOIN artist_relations ar ON ar.mp3ID = m.ID
LEFT JOIN artists a ON a.ID = ar.artistID
GROUP BY m.ID
ORDER BY ID
LIMIT 0,30;
";
if($result = $db->query($sql)){
echo "<table>";
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>".$row['Title']."</td>";
echo "<td>".$row['Artist']."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
此查询工作正常,但速度非常慢。
此数据库有 3 个字段:
`artists` : ID , Title
`mp3s` : ID , Title
`artist_relations` : mp3ID , artistID
我需要这个:
row1: titlemusic1 - artist1 , artist4 , artist5
row2: titlemusic2 - artist1
row3: titlemusic1 - artist3 , artist8
row4: titlemusic1 - artist9 , artist10
...
MP3s,艺术家和artist_relations各有超过20000条记录
EXPLAIN SELECT m.ID, m.Title, .... :
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE m ALL NULL NULL NULL NULL 23718 Using temporary; Using filesort
1 SIMPLE ar ALL NULL NULL NULL NULL 24337
1 SIMPLE a eq_ref PRIMARY PRIMARY 4 ganools_rj.ar.artistID 1
--
-- 表artist_relations
的表结构
如果不存在,则创建表 artist_relations
( artistID
int(11) 不为空, mp3ID
int(11) 不为空) 引擎=InnoDB 默认字符集=拉丁语1;
--
-- 表artists
的表结构
如果不存在,则创建表 artists
( ID
int(11) 不空AUTO_INCREMENT, Title
瓦尔查尔(155) 不为空 主键 ( ID
)) 引擎=InnoDB 默认字符集=拉丁语1 AUTO_INCREMENT=9005 ;
--
-- 表mp3s
的表结构
如果不存在,则创建表 mp3s
( ID
int(11) 不为空AUTO_INCREMENT, Title
瓦尔查尔(155) 不为空, imageURL
瓦尔查尔(155) 不为空, mp3URL
瓦尔查尔(155) 不为空, Description
文本, Lyric
文本, album
瓦尔查尔(155) 默认空, plays
int(11) 默认空, pubDate
日期不为空, 主键 ( ID
)) 引擎=InnoDB 默认字符集=拉丁语1 AUTO_INCREMENT=22936 ;
尝试为 artist_relations.mp3ID、artist_relations.artistID 和 mp3s.ID 创建索引。请参阅创建索引