2012-05-12 30 views
0

我正在嘗試創建一個顯示每個玩家統計數據的頁面。總進球,助攻,黃牌,紅牌等總和每個玩家的統計總和(目標/助攻/牌等)

詳細信息存儲在matchdetails你可以看到下面:

+----------------+-------------+------+-----+---------+-------+ 
| Field   | Type  | Null | Key | Default | Extra | 
+----------------+-------------+------+-----+---------+-------+ 
| player_id  | int(4)  | NO |  | NULL |  | 
| match_id  | int(4)  | NO |  | NULL |  | 
| season   | varchar(45) | NO |  | NULL |  | 
| player_present | int(4)  | NO |  | NULL |  | 
| player_away | int(4)  | NO |  | NULL |  | 
| goals   | int(4)  | NO |  | NULL |  | 
| assists  | int(4)  | NO |  | NULL |  | 
| yellowcards | int(4)  | NO |  | NULL |  | 
| redcards  | int(4)  | NO |  | NULL |  | 
+----------------+-------------+------+-----+---------+-------+ 

+-----------+----------+-----------+----------------+-------------+-------+---------+-------------+----------+ 
| player_id | match_id | season | player_present | player_away | goals | assists | yellowcards | redcards | 
+-----------+----------+-----------+----------------+-------------+-------+---------+-------------+----------+ 
| 3   | 1  | 2011-2012 | 1    | 0   | 0  | 0  | 0   | 0  | 
| 4   | 2  | 2011-2012 | 1    | 0   | 0  | 2  | 1   | 0  | 
| 4   | 1  | 2011-2012 | 1    | 0   | 0  | 0  | 0   | 0  | 
| 1   | 2  | 2011-2012 | 1    | 0   | 4  | 0  | 0   | 0  | 
| 1   | 1  | 2011-2012 | 0    | 1   | 0  | 0  | 0   | 0  | 
| 2   | 1  | 2011-2012 | 1    | 0   | 2  | 0  | 1   | 0  | 
| 2   | 2  | 2011-2012 | 1    | 0   | 1  | 2  | 0   | 1  | 
+-----------+----------+-----------+----------------+-------------+-------+---------+-------------+----------+ 

我想實現的事情是看到一排正在顯示他所有比賽的球員(player_present) ,總比分(player_away),總進球數,總助攻數,總黃牌數和總紅牌數。

我使用的以下代碼已經顯示了總得分,但它總計了所有球員得分的總進球數。我希望它能夠顯示每個球員的每一個細節的總和。

$sql = "SELECT SUM(goals) AS goals, 
player_id 
FROM matchdetails 
ORDER BY player_id ASC 
"; 
$results = $db->query($sql); 

echo "<table border='0' id='stats' cellpadding='0' cellspacing ='0'> 
foreach ($results as $row) {  
    echo "<td class=''>" , $row['player_id'] , ' ' , "</td>"; 
    echo "<td class=''>" , $row['goals'] , "</td>"; 
} 
    echo "</tr>"; 
echo "</table>"; 

回答

1

添加GROUP BY條款:

SELECT SUM(goals) AS goals, player_id 
FROM matchdetails 
GROUP BY player_id 
ORDER BY player_id ASC 
1

您需要使用GROUP BY,如果你想使用SUM

SELECT SUM(goals) AS goals, player_id 
FROM matchdetails 
GROUP BY player_id 
ORDER BY player_id ASC 

而且,不知道是否複製/粘貼錯誤或不,你缺少代碼中的收盤報價:

$sql = "SELECT SUM(goals) AS goals, 
player_id 
FROM matchdetails 
ORDER BY player_id ASC 
"; 
$results = $db->query($sql); 

echo "<table border='0' id='stats' cellpadding='0' cellspacing ='0'>"; 
foreach ($results as $row) {  
    echo "<td class=''>" , $row['player_id'] , ' ' , "</td>"; 
    echo "<td class=''>" , $row['goals'] , "</td>"; 
} 
    echo "</tr>"; 
echo "</table>"; 
+0

謝謝,這工作。缺少的結束報價確實是複製/粘貼錯誤。 – Johan

+0

@Joost:沒問題。如果我的回答是正確的,您應該通過點擊此答案的投票計數下方的大綠色勾號來接受它。只有接受它,如果它確實是正確的答案! –

+1

我還需要等幾分鐘才能接受它:p – Johan