从结果 table 生成体育联盟 table

generating sports league table from results table

我有一个 table 包含联赛中所有球队的赛程和结果。我正在尝试从结果中生成排名 table。我以为我让它工作了但是在手动计算排名时它与 MySql 输出的 table 不匹配。

$query_away = " Select teams.team_name,
    SUM(if(fixtures.away_team_score > fixtures.home_team_score,3,0)) AS W,
    SUM(IF(fixtures.away_team_score = fixtures.home_team_score,1,0)) AS D,
    SUM(IF(fixtures.away_team_score < fixtures.home_team_score,0,0)) AS L
FROM teams
 INNER JOIN fixtures ON teams.team_name = fixtures.home_team 
 GROUP BY fixtures.home_team
 ORDER BY W DESC";

这似乎是为未获胜的球队分配未获得的 3 分。有没有更简单的方法来实现这个或修复我的代码的方法? 总而言之,我试图计算客队出局对主队得分的次数,并为此分配 3 分。与对手平局得 1 分,输球得 0 分。

Fiddle http://sqlfiddle.com/#!9/85813/1

编辑

此查询重复两次,一次是针对主场排名,一次是针对客场排名。在 away_team 上加入客场查询解决了未获得的 3 分问题,但是如果我可以通过一个查询获得排名,这将有所帮助。下面的代码。

$fullTable = [];
$sortedTable = [];

$query_away = " Select teams.team_name,
    SUM(if(fixtures.away_team_score > fixtures.home_team_score,3,0)) AS W,
    SUM(IF(fixtures.away_team_score = fixtures.home_team_score,1,0)) AS D,
    SUM(IF(fixtures.away_team_score < fixtures.home_team_score,0,0)) AS L
 FROM teams
 INNER JOIN fixtures ON teams.team_name = fixtures.away_team 
 GROUP BY fixtures.away_team
 ORDER BY W DESC";



$query_home = " Select teams.team_name, 
    SUM(if(fixtures.home_team_score > fixtures.away_team_score,3,0)) AS W,
    SUM(IF(fixtures.home_team_score = fixtures.away_team_score,1,0)) AS D,
    SUM(IF(fixtures.home_team_score < fixtures.away_team_score,0,0)) AS L
 from teams
 inner join fixtures on teams.team_name = fixtures.home_team 
 GROUP BY fixtures.home_team
 order by W desc";


$home_result = mysqli_query($dbc, $query_home);
$away_result = mysqli_query($dbc, $query_away);
echo'<table><tr><th>Home Table</th><th>W</th><th>D</th><th>L</th><th>Pts</th></tr>';
if (!$home_result) {
    echo 'no result';
} else {
    //print_r(mysqli_fetch_array($result));

    while ($row = mysqli_fetch_array($home_result)) {
        $pts = $row['W'] + $row['D'];
        echo "<tr><td>" . $row['team_name'] . "</td><td>" . $row['W'] / 3 . "</td><td>" . $row['D'] . "</td><td>" . $row['L'] . "</td><td>" . $pts . "</td><tr>";
        $homeTeam = $row['team_name'];
    $fullTable["$homeTeam"] = $pts;
}
    echo'</table>';
}

如果主场和客场同时获胜,此查询应获得 3 分。平局只需要一笔金额,因为球队是主场还是客场并不重要。损失真的不需要总和,因为无论如何你只是把一堆零加起来。

SELECT teams.team_name,
    SUM(if(teams.team_name = fixtures.away_team 
        AND fixtures.away_team_score > fixtures.home_team_score,3,0)) 
    + SUM(if(teams.team_name = fixtures.home_team 
        AND fixtures.home_team_score > fixtures.away_team_score,3,0)) AS W,
    SUM(IF(fixtures.away_team_score = fixtures.home_team_score,1,0)) AS D,
    0 AS L
FROM teams
INNER JOIN fixtures ON teams.team_name = fixtures.home_team 
    OR teams.team_name = fixtures.away_team
GROUP BY teams.team_name
ORDER BY W DESC