2012-09-15 92 views
2

我想在我的sql查詢中做幾個JOINS,但遇到了問題。我需要做的是從poker_sites表中選擇所有字段,然後從networks搶2個相關領域和(如果可用)獲得的平均評分editor_contentSQL JOIN多表&獲取AVG

我遇到的問題是查詢僅返回一行時,有應該至少有三個。

任何幫助將不勝感激。

這裏是我的SQL

SELECT AVG(editor_content.rating) AS rating, poker_sites.*, 
networks.network_name, networks.network_icon FROM poker_sites 
    LEFT JOIN networks 
    ON (poker_sites.network_id=networks.network_id) 
    LEFT JOIN editor_content 
    ON (poker_sites.site_id=editor_content.assign_id) 
    WHERE poker_sites.published=1 

回答

5

您需要GROUP BY,如果你想獲得與聚合函數(在這種情況下AVG)多個結果。

SELECT x.avgRating AS rating, poker_sites.*, 
     networks.network_name, networks.network_icon 
    FROM poker_sites 
    LEFT JOIN networks 
     ON (poker_sites.network_id=networks.network_id) 
    LEFT JOIN 
    (
     SELECT AVG(editor_content.rating) as avgRating, editor_content.assign_id 
     FROM editor_content 
     GROUP BY editor_content.assign_id 
    ) x 
     ON (poker_sites.site_id = x.assign_id) 
    WHERE poker_sites.published=1