douyan4900 2012-06-30 19:05
浏览 34
已采纳

将2个查询合并为1个

I'm looking to optimize two queries into one, if possible.

My first query searches for all the authors of a lyrics... Then, for each author found, i want to find the total numbers of lyrics the author was involded in...

Right now, im executing the first query and for each row found, i'm launching another query to get the authors total lyrics he was involved... So, if there is 4 authors i will end up launching 4 more queries... That is to many queries in my opinion. That is why i've decided to write here, so i can get help on how to optimize my query...

This is the query i'm executing to get the author(s) responsable for a lyrics:

$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 ";

This is the query to get the total number of lyrics the author as writing:

$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";

This is a sample of the code:

<?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();
?>

Is it posible to optimize this query? If yes, how? Is there a link you could refer, so i can learn...

Thanks Marco

  • 写回答

2条回答 默认 最新

  • douyi0902 2012-06-30 19:17
    关注
    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条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能