Mysql查询 - 无法弄清楚这样做的方法

时间:2012-07-13 17:43:24

标签: mysql

INSERT INTO `table` (`game_id`, `first`, `second`, `third`)
VALUES
    (1, 'jack', 'joe', 'pat'),
    (2, 'jack', 'joe', 'jess'),
    (3, 'pat', 'jess', 'jack'),
    (4, 'pat', 'jess', 'jack');

这是一个统计表,每个游戏都有前三名玩家。我希望拉出所有玩家并相应地订购。

First place - 3 points
Second place - 2 points
Third place - 1 point

所以,它应该返回:

id  player  points
1   jack    8
2   pat     7
3   jess    5
4   joe     4

我无法通过一个查询找到一种方法。

1 个答案:

答案 0 :(得分:3)

Select player, sum(points) as points from (
Select `first` as player, count(`first`)*3 as points From gameStats group by `first` 
union all
Select `second` as player, count(`second`)*2 as points From gameStats group by `second` 
union all
Select `third` as player, count(`third`)*1 as points From gameStats group by `third` ) as tmp group by player

这应该这样做。

让我知道您是否需要更多帮助。