2016-12-17 71 views
0

我有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); 

我必須做出一個名爲「榜」含表:

player_id,player_name,total_wins,total_matches 

如何進行?

+1

你再拍create table語句...不清楚你是如何計算的總戰績 –

+0

你的意思是,希望查詢返回有這些列的表格和明顯的含義? – philipxy

回答

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; 

在線例如:http://rextester.com/EHDCG19917