复杂的足球联盟MySQL中的动态排序?

Dan*_*Dan 4 php mysql

我有一个足球联赛的表'游戏'如下:

date    home_team_id    away_team_id    home_score      away_score
 -          1                 2              6             21
 -          3                 1              7             19
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何动态生成由Wins订购的团队ID列表(然后指向if if)?

-

我有这个查询,当我有一个$ team_id时工作正常但是因为我一次只能做一个团队,这不允许在查询级别进行排序

((SELECT COUNT(*) FROM `games` WHERE ((`home_score` > `away_score`) AND `home_team_id` = '.$team_id.')) + 
(SELECT COUNT(*) FROM `games` WHERE ((`home_score` < `away_score`) AND `away_team_id` = '.$team_id.'))) AS `wins`
Run Code Online (Sandbox Code Playgroud)

我想知道我是否可以使用某种形式的GROUP,或者mySQL可以知道$ team_id本身?我还尝试了一些带有'team'表的多个JOIN,但它们也没有用.

谢谢,

Sim*_*mon 5

让我们一步一步来做:

选择主场赢得的比赛和主场比分:

   SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G WHERE 
      G.team_id = T.team_id #See 3. query and you'll understand
      G.home_score > away_score
Run Code Online (Sandbox Code Playgroud)

我们将此结果称为HOME_GAMES.

选择赢得的比赛和客场比赛的得分:

SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
WHERE 
  G.team_id = T.team_id #See 3. query and you'll understand
  G.away_score > G.home_score
Run Code Online (Sandbox Code Playgroud)

我们将此结果称为AWAY_GAMES.

选择赢得的总比赛和总分:

   SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM
   (AWAY_GAMES) AS A, (HOME_GAMES) AS H, teams T 
   ORDER BY total_wins, total_score
Run Code Online (Sandbox Code Playgroud)

==>通过替换AWAY_GAMES和HOME_GAMES将所有内容放在一起:

SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM 
  (SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
   WHERE 
     G.team_id = T.team_id #See 3. and you'll understand
     G.away_score > G.home_score) AS A, 

   (SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G 
   WHERE 
      G.team_id = T.team_id #See 3. and you'll understand
      G.home_score > away_score) AS H, 

   teams T
   ORDER BY total_wins, total_score 
Run Code Online (Sandbox Code Playgroud)