从结果表生成体育联赛表

时间:2015-04-28 22:12:34

标签: php mysql select join count

我有一张桌子,其中包含联盟球队和比赛结果中的所有球队。我试图从结果中生成一个排名表。我以为我有它工作,但在手动计算积分时,它与MySql输出的表格不匹配。

$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的对手并列失败。

小提琴http://sqlfiddle.com/#!9/85813/1

修改

对于主场积分,此查询重复两次,对于积分榜,重复一次。加入away_team上的离开查询修复了未实现的3pts问题,但如果我能从一个查询中获得排名,那将会有所帮助。代码如下。

$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>';
}

1 个答案:

答案 0 :(得分:1)

此查询应同时为主场和客场的胜利获得三分。领带只需要一笔钱,因为如果球队在家或离开都无关紧要。损失实际上不需要总和,因为无论如何你只是加了一堆零。

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