MySQL查询与匹配和总结 - 联盟表

时间:2014-04-06 18:07:04

标签: mysql

我有5张桌子:

  • 玩家(id,name,team_id)
  • 团队(身份证,姓名)
  • 结果(id,game_id,player.id,位置)
  • 游戏(身份证,地点)
  • 得分(位置,得分)

follows

enter image description here

我想制作像this

这样的联赛表

enter image description here

我很困惑如何总结每位球员的得分。到目前为止,这是我的代码:

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

有什么想法吗?

2 个答案:

答案 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