2012-06-30 195 views
3

如果可能,我期待將兩個查詢優化爲一個。對於歌詞的所有作者將2個查詢合併爲1

我的第一個查詢搜索......然後,對於每個筆者發現,我想找到歌詞的總數筆者在...

被involded眼下,即時通訊執行第一個查詢,並找到每一行,我正在啓動另一個查詢,以獲取作者的歌詞,他參與了...因此,如果有4名作者,我將最終啓動4個更多的查詢... 這就是在我看來很多疑問。這就是爲什麼我決定寫在這裏,所以我可以得到如何優化我的查詢幫助...

這是我正在執行的查詢讓作者(s)負責歌詞:

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

可以優化此查詢嗎?如果是,如何?有沒有什麼可以參照,所以我可以瞭解這是作爲赫克混亂的鏈接...

感謝 馬爾科

+0

您應該刪除從查詢行'@'。在那裏隱藏錯誤意味着你將無法看到任何錯誤。這可能會導致一些困難,試圖弄清楚發生了什麼。 –

+0

你的代碼易受SQL注入攻擊。使用時,任何腳本小孩都可以侵入您的數據庫。我強烈建議您在開始構建嚴肅的Web應用程序之前閱讀一些基本的安全性。 – AardvarkSoup

+0

不擔心安全性......如上所述,這是一個示例代碼,出於可讀性的目的,而不是真正的代碼...我已經照顧了真正的代碼中的sql注入... – Marco

回答

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 
+0

感謝兄弟!這完美,易於理解! – Marco

1

。當你有一個名爲「歌詞」的屬性時,爲什麼你傳入一個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 

我想......

+0

我編輯了我的示例代碼(示例,不是真正的代碼),就在您編寫答案時...對不起 – Marco