我有2张桌子
create table players
(name text,
id serial primary key);
create table matches
(winner integer references players(id),
loser integer references players(id),
id serial primary key);
我必须制作一个名为“standings”的表,其中包含:
player_id,player_name,total_wins,total_matches
如何进行?
答案 0 :(得分:0)
这样的事情:
select p.id, p.name,
count(w.id) as total_wins,
count(l.id) + count(w.id) as total_matches
from players p
left join matches w on w.winner = p.id
left join matches l on l.loser = p.id
group by p.id, p.name;