1

我试图拉出一个团队的输赢记录,在这种情况下是团队 1。团队可以玩多种格式,记录对这些进行相应的分组。它工作得很好,除非一支球队没有以某种格式打平(可能也是为了获胜,但我在数据库中没有任何不赢的球队),然后它拒绝获取该格式的任何数据. 我需要它为绘图返回一个零,从而显示该格式的其余结果。查询如下:

SELECT matches.format, count(id) as played, a.wins, b.draws, count(id)-a.wins-b.draws as loss
FROM matches 

INNER JOIN (SELECT format, count(id) as wins 
FROM matches 
WHERE winner=1
GROUP BY format) as a ON matches.format=a.format

INNER JOIN (SELECT format, count(id) as draws 
FROM matches 
WHERE hometeam=1 
AND winner=-1 
OR awayteam=1  
AND winner=-1) as b ON matches.format=b.format

WHERE matches.hometeam=1
OR matches.awayteam=1
GROUP BY format

这返回

format played wins draws loss
  1      14     9   1     4

但完全忽略了这支球队也打过6场“2”赛制,4胜2负,没有平局。任何帮助将非常感激

4

2 回答 2

1

我认为你问题的关键是but with no draws。听起来您应该使用 anOUTER JOIN而不是INNER JOIN

SELECT matches.format, count(id) as played, coalesce(a.wins,0) wins, coalesce(b.draws,0), count(id)-coalesce(a.wins,0)-coalesce(b.draws,0) as loss
FROM matches 
    LEFT JOIN (
        SELECT format, count(id) as wins 
        FROM matches 
        WHERE winner=1
        GROUP BY format
    ) as a ON matches.format=a.format
    LEFT JOIN (
        SELECT format, count(id) as draws 
        FROM matches 
        WHERE hometeam=1 
            AND winner=-1 
            OR awayteam=1  
            AND winner=-1
    ) as b ON matches.format=b.format
WHERE matches.hometeam=1
    OR matches.awayteam=1
GROUP BY matches.format

小心使用 AND... OR - 您可能需要括号...

现在进行优化:

SELECT format, 
    count(id) played,
    sum(if(winner=1,1,0)) wins,
    sum(if(winner=-1,1,0)) draw,
    count(id)-sum(if(winner=1,1,0))-sum(if(winner=-1,1,0)) loss
FROM matches
WHERE hometeam=1 OR awayteam=1
GROUP BY format
于 2013-04-02T04:11:14.117 回答
0
  SELECT matches.format,
         count(id) as played,
         count(case when winner=1 then 1 end) wins,
         ifnull(count(case when winner=-1 then 1 end),0) draw,
         count(case when winner not in (1,-1) then 1 else 0 end) loss
    FROM matches
   WHERE matches.hometeam=1 OR matches.awayteam=1
GROUP BY format
于 2013-04-02T04:12:20.200 回答