所以我有两张桌子,球员和比赛,结构如下:
Table "public.players"
Column | Type | Modifiers
--------+---------+------------------------------------------------------
id | integer | not null default nextval('players_id_seq'::regclass)
name | text |
wins | integer | default 0
loses | integer | default 0
rating | integer | default 1500
和
Table "public.matches"
Column | Type | Modifiers
---------------+---------+------------------------------------------------------
id | integer | not null default nextval('matches_id_seq'::regclass)
player1 | integer |
player1rating | integer |
player2 | integer |
player2rating | integer |
winner | boolean |
如果 player1 赢得那场比赛,则获胜者为 true,如果 player2 赢得那场比赛,则为 false。
使用球员表进行简单的赢/输比较很容易,但是我正在观察两个球员面对面的比较,他们的记录是什么。
所以我对如何总结给定玩家可能被列为玩家1或玩家2的条件感到困惑:P1获胜:
(player1 = <player1> AND winner = true) OR (player2 = <player1> AND winner = false)
P2胜:
(player1 = <player2> AND winner = true) OR (player2 = <player2> AND winner = false)
损失将与其他玩家获胜相反。
返回信息的东西,例如:
id | name | wins | loses | rating | wins_v_opp | loses_v_opp
------+----------+------+-------+--------+------------+------------
4200 | Sinku | 5 | 48 | 1191 | 1 | 4
4201 | Kenshiro | 33 | 29 | 1620 | 4 | 1
我在下面的update2之前想出了什么:
CREATE FUNCTION matchup(text, text) AS $$
DECLARE
player1_name ALIAS FOR $1;
player2_name ALIAS FOR $2;
BEGIN
EXECUTE 'SELECT id FROM player WHERE name LIKE $1'
INTO player1_id
USING player1_name;
IF NOT FOUND THEN
RAISE EXCEPTION 'Player1 % not found', player1_name;
END IF;
EXECUTE 'SELECT id FROM player WHERE name LIKE $1'
INTO player2_id
USING player2_name;
IF NOT FOUND THEN
RAISE EXCEPTION 'Player2 % not found', player2_name;
END IF;
RETURN QUERY EXECUTE 'WITH cte_winners AS (
SELECT
CASE WHEN winner THEN m.player1 ELSE m.player2 END AS player,
COUNT(*) AS wins_v_opp,
sum(count(*)) over() - COUNT(*) AS loses_v_opp
FROM matches AS m
WHERE player1 IN ($1,$2) AND player2 IN ($1,$2)
GROUP BY player
)
SELECT * FROM players AS p
LEFT OUTER JOIN cte_winners AS cw ON cw.player = p.id WHERE p.id IN ($1,$2)'
USING player1_id,player2_id;
END;
$$ LANGUAGE plpgsql;