gpt4 book ai didi

sql - PostgreSQL:如果表存在则返回函数否则 View 中为0

转载 作者:行者123 更新时间:2023-11-29 13:27:41 25 4
gpt4 key购买 nike

我无法让 PostgreSQL 识别匹配表为空,因此应该为下面 View 中的 wins 和 matches 列输出 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. 您不需要 case 因为 count(null) 给出 0。
  2. 你应该left join 匹配,以防给定玩家没有匹配。
  3. 您应该加入 比赛两次以获得输赢次数。

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;

关于sql - PostgreSQL:如果表存在则返回函数否则 View 中为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30740796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com