2012-07-13 45 views
2
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'); 

这是一个统计表,每个游戏的前三名球员。我期待拉动所有的球员,并相应地订购他们。Mysql查询 - 无法想出办法做到这一点

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 

我不能想出一个办法,用一个查询来做到这一点。

+0

你不应该在你的表中有字符串,你也不应该命名一个表格 – Ghost 2012-07-13 17:49:09

+0

@Ghost实际的表更复杂,只包含数字。我为这个问题做了这个。 – domino 2012-07-13 17:51:20

+0

@Ghost为什么表中不应该有字符串? – octern 2012-07-13 17:53:49

回答

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 

这应该做到这一点。

让我知道你是否需要任何帮助。

+0

太棒了,谢谢。 – domino 2012-07-13 18:05:17

相关问题