2015-06-09 54 views
1

我無法讓PostgreSQL識別匹配表爲空,因此應在下面的視圖中爲勝利和匹配列輸出0。相反,我一直在空洞的看法。當我得到一個「玩家ID」,「玩家ID」,0,每行0。可能是什麼問題呢?PostgreSQL:如果表存在返回函數其他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
  1. 你不需要case因爲count(null)給出0
  2. 你應該情況下left join比賽不存在一個給定的球員比賽。
  3. 你應該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; 
+0

有道理!謝謝! – KishB87

相關問題