我无法让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;
答案 0 :(得分:1)
case
,因为count(null)
给出了0。left join
匹配。join
两次匹配才能获得胜负次数。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;