我有5张桌子:
我想制作像this
这样的联赛表
我很困惑如何总结每位球员的得分。到目前为止,这是我的代码:
SELECT Players.name, Teams.name, Results.position FROM Players
INNER JOIN Teams ON Players.team_id = Teams.id
JOIN Results ON Player.id = Results.player_id
JOIN Scores ON Results.position = Scores.scores
有什么想法吗?
答案 0 :(得分:2)
SELECT Players.name,
Teams.name,
sum(Results.position * Scores.scores) as scores
FROM Players
JOIN Teams ON Players.team_id = Teams.id
JOIN Results ON Player.id = Results.player_id
JOIN Scores ON Results.position = Scores.scores
GROUP BY Players.name, Teams.name
答案 1 :(得分:0)
要列出所有玩家(无论他们是否出现在结果表中),您必须使用LEFT JOIN
。
SELECT p.name player_name,t.name team_name,SUM(COALESCE(s.score,0)) as total_score
FROM players p
INNER JOIN teams t ON t.id = p.team_id
LEFT JOIN results r ON p.id = r.player_id
LEFT JOIN scores s ON s.position = r.position
GROUP BY p.id
ORDER BY total_score desc