3

如果可能的话,我希望将两个查询优化为一个。

我的第一个查询搜索歌词的所有作者......然后,对于找到的每个作者,我想找到作者参与的歌词总数......

现在,我正在执行第一个查询,并且对于找到的每一行,我正在启动另一个查询以获取他所涉及的作者的总歌词......所以,如果有 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();
?>

是否可以优化此查询?如果是,如何?有没有链接可以参考一下,学习一下。。。

谢谢马可

4

2 回答 2

1
SELECT
  author.author_id,
  author.name,
  COUNT(DISTINCT more_tracks.lyrics_id) AS total
FROM track
INNER JOIN lyrics_author USING (lyrics_id)
INNER JOIN author USING (author_id)
LEFT JOIN lyrics_author AS more_tracks USING (author_id)
WHERE track.track_id = $trackid
GROUP BY author.author_id
于 2012-06-30T19:17:45.290 回答
1

这真是令人困惑。当你有一个叫做歌词id的属性时,你为什么要传入一个trackid作为歌词ID?反正

Select author.author_id, author.name, Count(*)
inner join
(SELECT lyrics_author.author_id 
FROM lyrics_author 
INNER JOIN tracks ON track.lyrics_id = lyrics_author.lyrics_id 
WHERE track.track_id = $lyricsid"; 
)  as lyricalauthors
inner join lyrics_author on lyrics_author.author_id = lyricalauthors.author_id
On author.author_id = lyricalauthors.author_id
Group By Author.author_id,author.name

我认为 ...

于 2012-06-30T19:33:13.007 回答