MySQL搜索值分为两列和第三列

时间:2018-01-11 23:05:37

标签: mysql sql

在我的表“game_info”中我有

ID | player_1 | player_2 | score
--------------------------------
1  | John     | Rick     | 100
2  | Joe      | John     |  80 
3  | Bob      | Rick     | 210

我想总结每位玩家的总分,无论他们是player_1还是player_2并按分数排序 我的期望是:

Name | Score
------------
Rick | 310
Bob  | 210
John | 180
Joe  |  80

我曾尝试过JOIN和UNION,但我做不到。

有没有办法在sql中执行此操作,或者我必须重新设计我的表?

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用union allgroup by

执行此操作
select player, sum(score)
from ((select player1 as player, score from game_info
      ) union all
      (select player2 as player, score from game_info
      )
     ) p
group by player
order by sum(score) desc;

答案 1 :(得分:0)

SELECT player, SUM(score)
FROM
(SELECT player_1 AS player, score
 FROM t
 UNION ALL
 SELECT player_2 as player, score
 FROM t) sub
GROUP BY player

你必须将玩家1的结果与玩家2的结果结合起来,这样你才能得到一个只有玩家和得分的结果。当然,在这个视图中,分数将被列出两次,每个玩家一个。在我的查询中,结果称为sub。基于sub,您可以按玩家分组并总结他们的分数。