我试图显示玩家得分的统计数据,但是有时同一个玩家被添加到具有相同玩家ID的数据库中,当玩家被添加两次时我如何将这些值一起添加以显示为总数,而不是回声玩家两次.
db结构示例:
playerID | Goals | Season | leagueID
1 5 1 1
2 1 1 1
1 2 1 2
5 3 1 1
1 3 2 2
2 2 2 1
Run Code Online (Sandbox Code Playgroud)
PHP:
$query = $db->query('SELECT * FROM playerstats ORDER BY goals DESC LIMIT 30');
$num = $query->num_rows;
if($num > 0) {
foreach($query as $row) {
$playerID = $row['playerID'];
$goals = $row['goals'];
echo '
<tr>
<td>'.$playerID.'</td>
<td>'.$goals.'</td>
</tr>
';
}
}
Run Code Online (Sandbox Code Playgroud)
这将显示玩家ID 1,3分开的时间.如何让所有目标加在一起只显示一次playerID 1(10)
我已经尝试将查询更改为:SELECT DISTINCT*FROM playerstats ORDER BY目标DESC LIMIT 30但这没有任何区别.
Group BY将帮助您:
<?php
$query = $db->query('SELECT SUM(p.goals) as total_goals,
p.playerID, p.leagueID, p.Season
FROM playerstats as p
GROUP BY p.playerID, p.leagueID, p.Season
ORDER BY total_goals DESC LIMIT 30');
$num = $query->num_rows;
if($num > 0) {
foreach($query as $row) {
echo '
<tr>
<td>'.$row['playerID'].'</td>
<td>'.$row['total_goals'].'</td>
</tr>
';
}
Run Code Online (Sandbox Code Playgroud)
}
请注意,我的查询也会根据赛季和联赛进行分组,如果你想要通过赛季和联赛的总进球,你的group by意志是:
GROUP BY p.playerID
如果你只想要playerID和的总和goals不是无所谓的Season或leagueID更改查询到:
SELECT DISTINCT playerID AS player,
(SELECT SUM(goals) FROM playerstats WHERE playerID = player) AS totalGoals
FROM playerstats
| 归档时间: |
|
| 查看次数: |
1152 次 |
| 最近记录: |