2012-08-23 44 views
0

我有這些SQL查詢(我用笨DB類):這是很好的SQL查詢資源嗎?

 $query = $this->db->select("a.title AS articles_title, 
        a.content AS articles_content, 
        a.excerpt AS articles_excerpt, 
        a.slug AS articles_slug, 
        a.views AS articles_views, 
        a.views AS articles_views, 
        CONCAT(up.first_name, ' ', up.last_name) AS articles_author, 
        DATE_FORMAT(a.created, '%T %d.%m.%Y') AS articles_created, 
        (SELECT IF(ROUND(AVG(av.vote),1), ROUND(AVG(av.vote),1), 0) FROM articles_votes av WHERE a.id = av.article_id) AS articles_votes, 
        (SELECT COUNT(ac.id) FROM articles_comments ac WHERE a.id = ac.article_id) AS articles_totalcomments", FALSE) 
      ->from('articles a') 
      ->join('user_profiles up', 'a.author_id = up.user_id') 
      ->where('page_id', $page_id) 
      ->order_by("a.$ordering") 
      ->get(); 

這是好服務器和速度的資源呢?或者我應該創建另一個計數投票和評論的功能,它將計算所有評論和平均投票數,並將其添加到文章數組中?

感謝您使用

+0

當然,它不是一個有效的查詢,因爲它使用多個子查詢。 – Raptor

回答

0

資源和查詢計劃的效率取決於基礎數據庫,當然,所產生的實際的SQL。使用SQL分析工具來確保您瞭解查詢實際結果的方式總是很好。

這就是說。有時你可以得到更好的性能轉向這樣的事情:

SELECT 
    a.student_id, 
    a.name, 
    (select sum(s.score) from scores s where s.student_id = a.student_id) as total_score 
FROM students a 

爲了這樣的事情:

SELECT 
    a.student_id, 
    a.name, 
    tot.score 
FROM students a 
JOIN (
    SELECT student_id, 
      sum(score) 
    FROM scores 
    GROUP BY student_id 
) as tot ON tot.student_id = a.student_id 

如果列表達包括上沒有索引列的查詢,則可能需要進行全表每次運行時都進行掃描。在我的示例中,我在連接結果中包含一個鍵,以便查詢完成一次,然後您可以在外部選擇中進行查詢。

希望有所幫助。

+0

謝謝。所以我的解決方案比具有兩個或更多查詢和PHP foreach功能的解決方案更好,不是嗎? – shanoy

+0

最有可能的是 – oshea00