如果可能的话,我希望将两个查询优化为一个。
我的第一个查询搜索歌词的所有作者......然后,对于找到的每个作者,我想找到作者参与的歌词总数......
现在,我正在执行第一个查询,并且对于找到的每一行,我正在启动另一个查询以获取他所涉及的作者的总歌词......所以,如果有 4 个作者,我最终会再启动 4 个查询......在我看来,这是许多疑问。这就是我决定在这里写的原因,这样我就可以获得有关如何优化查询的帮助...
这是我正在执行的查询,以使作者对歌词负责:
$sql = "SELECT author.author_id, author.name
FROM track INNER JOIN lyrics_author ON track.lyrics_id = lyrics_author.lyrics_id
INNER JOIN author ON lyrics_author.author_id = author.author_id
WHERE track.track_id = $trackid ";
这是获取作者所写歌词总数的查询:
$total = "SELECT lyrics_author.author_id, count(*) as total
FROM lyrics_author
WHERE lyrics_author.author_id = $author_id
GROUP BY lyrics_author.author_id";
这是代码示例:
<?php
$trackid = 5;
$sql = "SELECT author.author_id, author.name
FROM track INNER JOIN lyrics_author ON track.lyrics_id = lyrics_author.lyrics_id
INNER JOIN author ON lyrics_author.author_id = author.author_id
WHERE track.track_id = $trackid ";
$result_author = @ $conn->query($sql);
while ($row_author = $result_author->fetch_assoc()) {
$author_id = $row_author['author_id'];
$total = "SELECT lyrics_author.author_id, count(*) as total
FROM lyrics_author
WHERE lyrics_author.author_id = $author_id
GROUP BY lyrics_author.author_id";
$result_total_lyrics = @ $conn->query($total);
$t = $result_total_lyrics->fetch_assoc();
echo $t['total'];
$result_total_lyrics->free();
}
$result_author->free();
?>
是否可以优化此查询?如果是,如何?有没有链接可以参考一下,学习一下。。。
谢谢马可