PostgreSQL:如果表存在于视图中的其他0,则返回函数

时间:2015-06-09 19:10:38

标签: sql postgresql

我无法让PostgreSQL识别匹配表是空的,因此应该为下面视图中的胜利和匹配列输出0。相反,我一直在看空视图。当我应该获得“玩家ID”,“玩家ID”,每行0,0。可能是什么问题?

CREATE VIEW player_standings AS
SELECT 
    players.id,
    players.name,
    CASE WHEN EXISTS (SELECT * FROM matches) THEN COUNT(matches.winner) ELSE 0 END AS wins,
    CASE WHEN EXISTS (SELECT * FROM matches) THEN COUNT(matches.winner) + COUNT(matches.loser) ELSE 0 END AS matches
FROM players
INNER JOIN matches
    ON players.id = matches.winner
GROUP BY players.id
ORDER BY
    wins DESC;

1 个答案:

答案 0 :(得分:1)

  1. 您不需要case,因为count(null)给出了0。
  2. 如果某位玩家没有匹配,您应left join匹配。
  3. 您应该join两次匹配才能获得胜负次数。
  4. CREATE OR REPLACE VIEW player_standings AS
    SELECT 
        p.id,
        p.name,
        COUNT(m1.winner) AS wins,
        COUNT(m1.winner) + COUNT(m2.loser) AS matches
    FROM players p
    LEFT JOIN matches m1
        ON p.id = m1.winner
    LEFT JOIN matches m2
        ON p.id = m2.loser
    GROUP BY p.id, p.name
    ORDER BY
        wins DESC;
    
相关问题