具有多列的SQL join语句

具有多列的SQL join语句,join,left-join,Join,Left Join,我有两张表,如下所示: 玩家: id | name | location 1 | john | australia 2 | anne | u.s. 3 | jen | germany 游戏: player | points | player2 | points2 john | 2 | anne | 1 anne | 1 | jen | 3 jen | 3 | john | 4 jen | 4 |

我有两张表,如下所示:

玩家:

id | name | location 
1  | john | australia
2  | anne | u.s. 
3  | jen  | germany 
游戏:

player | points | player2 | points2
john   | 2      | anne    | 1 
anne   | 1      | jen     | 3 
jen    | 3      | john    | 4 
jen    | 4      | anne    | 1 
我希望SQL语句返回每个玩家的姓名、位置以及每个玩家在其参加的所有游戏中累积的总积分。 我试图做一个左连接,但我无法让它工作

SELECT name, location, SUM(total_points) AS total_points
FROM (
    SELECT name, location, COALESCE(SUM(points), 0) AS total_points
    FROM players p
    LEFT JOIN games g ON p.name = g.player
    GROUP BY name, location
    UNION ALL
    SELECT name, location, COALESCE(SUM(points2), 0)
    FROM players p
    LEFT JOIN games g ON p.name = g.player2
    GROUP BY name, location
) x
GROUP BY name, location

对于上表,这产生了安妮-2、珍-3和约翰-14,这是不对的。嗯……BarmarFixed,我在中删除了<<代码>组的子句。你应该在<代码>游戏表中使用玩家ID,而不是No.@用户:如果解决了你的问题,你应该考虑接受答案。