mysql队伍A总得分

时间:2014-09-13 15:16:45

标签: php mysql

我试图找到A队在过去6场比赛(总数)中得分和受让的总数,无论TeamA是主队还是客队。 例如:我们假设$ teamA ='Arsenal'并搜索最后6个结果,

给出了以下结果:

Leicester City  1 - 1   Arsenal
Everton         2 - 2   Arsenal
Arsenal         2 - 1   Crystal Palace
Norwich City    0 - 2   Arsenal
Arsenal         1 - 0   West Bromwich Albion
Arsenal         3 - 0   Newcastle United

以上是获取最后6个结果的查询输出,现在我需要获得$ teamA和$ teamB的目标总数

$query = mysql_query("SELECT * FROM football WHERE `HomeTeam` = '$teamA' OR AwayTeam = '$teamA' ");

while ($row = mysql_fetch_array($query)){

  if ($row['HomeTeam'] = $teamA){  
    $teamAgoals = $teamAgoals + $row['FTHG'];
  }


  if ($row2['AwayTeam'] = $teamA){  
    $teamAgoals = $teamAgoals + $row['FTAG'];
  }
  $tot++;

  if ($tot == 7):
    exit;
  endif;
}

我遇到的问题是查询中的LIMIT返回最近6场主场比赛或最后6场客场比赛。

2 个答案:

答案 0 :(得分:0)

您可以使用case表达式来确定该团队是主队还是客队:

SELECT   SUM (CASE WHEN `HomeTeam` = '$teamA' THEN fthg ELSE ftag END)
FROM     football
WHERE    '$teamA' IN (`HomeTeam`, `AwayTeam`)
ORDER BY `MatchDate` DESC -- I'm guessing there's something like this
LIMIT    6

答案 1 :(得分:0)

@Mureinik我尝试了你的解决方案,经过一些调整后,我得到了我需要的答案,谢谢你的帮助。我开始得到这个错误

  

每个派生表都必须有自己的别名。

我添加了别名'总计'查询,它完美地运作。

SELECT SUM(CASE WHEN `HomeTeam` = 'Arsenal' THEN FTHG ELSE FTAG END) AS scored, SUM(CASE WHEN `AwayTeam` = 'Watford' THEN FTHG ELSE FTAG END) AS conceeded FROM ( SELECT Hometeam,Awayteam,FTHG,FTAG FROM football WHERE 'Arsenal' IN (`HomeTeam`, `Awayteam`) ORDER BY `id` DESC LIMIT 6) as totals