【发布时间】:2015-04-28 22:12:34
【问题描述】:
我有一张表格,其中包含一个联赛中所有球队的赛程和结果。我正在尝试从结果中生成一个排名表。我以为我已经成功了,但是在手动计算排名时它与 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 上的客场查询修复了不劳而获的 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>';
}
【问题讨论】:
-
带有示例数据的sql fiddle 会有所帮助。
-
您正在加入 teams.team_name = fixtures.home_team 上的团队表。这意味着当您执行
if away_team_score > home_team_score时,您将为失败的团队增加 3。 -
@Dagon fiddle 添加见 Q.
-
@Don'tPanic 你能解释一下吗
-
我认为如果你加入 team_name = away_team,你应该会得到你期望的结果。
标签: php mysql select join count