MySQL查询/体育表+时间表中的错误

时间:2014-06-21 15:24:02

标签: mysql sql

我的目的是根据我的日程安排创建排名,其中包含过去3个比赛日的结果。我有两张桌子,一张包含有关我的运动队的信息,另一张包含时间表。

现在我正在寻找一种方法将比赛结果列入积分榜。到目前为止一切正常,但我的查询没有正确计算第3个比赛日。第3场比赛日在每场比赛中均以1比1战平。

统计:

Team#1  3 Matches, 2 Wins, 0 Draws, 0 Losses
Team#2  3 Matches, 2 Wins, 0 Draws, 0 Losses

MySQL表“团队”:

MySQL table "teams"

MySQL表“competition_schedule”:

MySQL table "competition_schedule"

查询:

SELECT 
   id, 
   name, 
   logo, 
   SUM(matches) AS `matches`,
   SUM(w) AS `win`,
   SUM(d) AS `draw`,
   SUM(l) AS `loss`,
   SUM(goals) AS `goals`, 
   SUM(goals_against) AS `goals_against`, 
   (SUM(goals)-SUM(goals_against)) AS `dif`, 
   SUM(pts) AS `pts`
FROM(
   SELECT
     t.`id`, 
     t.`name`,
     t.`logo`,
     COUNT(cs.`public`) AS `matches`,
     SUM(cs.`home-team_score`) AS `goals`,
     SUM(cs.`guest-team_score`) AS `goals_against`,
     IF( cs.`home-team_score` > cs.`guest-team_score`, 3, 
         IF( cs.`home-team_score` = cs.`guest-team_score`, 1, 0 )
     ) AS `pts`,
     IF( cs.`home-team_score` > cs.`guest-team_score`, 1, 0) AS `w`,
     IF( cs.`home-team_score` = cs.`guest-team_score`, 1, 0) AS `d`,
     IF( cs.`home-team_score` < cs.`guest-team_score`, 1, 0) AS `l`
   FROM
     team t
   LEFT JOIN
     competition_schedule cs
   ON
     (
       t.`id` = cs.`home-team_id`
     )
   WHERE cs.`public`         = 1
   AND   cs.`season`         = 1
   AND   cs.`matchday`      <= 12
   AND    cs.`association_id` = 1
   GROUP BY t.`id`

UNION ALL

   SELECT
     t.`id`, 
     t.`name`, 
     t.`logo`,
     COUNT(cs.`public`) AS `matches`,
     SUM(cs.`guest-team_score`) AS `goals`,
     SUM(cs.`home-team_score`) AS `goals_against`,
     IF( cs.`guest-team_score` > cs.`home-team_score`, 3, 
       IF( cs.`guest-team_score` = cs.`home-team_score`, 1, 0 )
     ) AS `pts`,
     IF( cs.`guest-team_score` > cs.`home-team_score`, 1, 0) AS `w`,
     IF( cs.`guest-team_score` = cs.`home-team_score`, 1, 0) AS `d`,
     IF( cs.`guest-team_score` < cs.`home-team_score`, 1, 0) AS `l`
   FROM
     team t
   LEFT JOIN
     competition_schedule cs
   ON
     (
       t.`id` = cs.`guest-team_id`
     )
   WHERE cs.`public`         = 1
   AND   cs.`season`         = 1
   AND   cs.`matchday`      <= 12
   AND    cs.`association_id` = 1
   GROUP BY t.`id`    
 ) alle
 GROUP BY id
 ORDER BY pts DESC, dif DESC, goals DESC

0 个答案:

没有答案