将2个查询合并为1个

时间:2012-06-30 19:05:38

标签: php mysql

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

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

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

优化此查询是否可行?如果有,怎么样?有没有可以参考的链接,所以我可以学习......

由于 马可

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这令人困惑。当你有一个名为lyricsid的属性时,为什么你作为lyricsid传入trackid? 反正

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

我想......