将空结果检索为0 sql

时间:2013-04-02 04:02:03

标签: mysql sql

我试图拉动团队的赢/输记录,在这个实例中是团队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场没有平局。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

我认为你问题的关键是but with no draws。听起来你应该使用OUTER 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 ...或者 - 你可能需要括号......

现在进行优化:

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

答案 1 :(得分: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