我有一张包含这些列的表格:
id | player1_name | player1_score | player2_name | player2_score | player3_name | player3_score | player4_name | player4_score | player5_name | player5_score
如果只有一行,我如何获得最高playerX_score
和相应的playerX_name
?
我已尝试使用GREATEST()
,但我无法获得playerX_name
。
答案 0 :(得分:1)
另外,我认为您的表格设计得更好id | name | score | position | teamid
,其中position
从1到5,teamid
用于将同一个团队中的每个人组合在一起。这样可以使这种查询变得更加容易(每个团队得分最高的相关行)。
但是,这是使用当前表格执行所需操作的一种方法:
SELECT GREATEST(player1_score,player2_score,player3_score,
player4_score,player5_score) as score,
CASE GREATEST(...) -- repeat the above
WHEN player1_score then player1_name
WHEN player2_score then player2_name
WHEN player3_score then player3_name
WHEN player4_score then player4_name
WHEN player5_score then player5_name
END as name
FROM mytable
答案 1 :(得分:0)
我认为你的表结构不适合你想要做的事情。您希望数据库知道player1_name
和player1_score
之间存在某种关系,但这并未在表中进行编码。一个让这更容易的变化就是给每个玩家自己的记录,并使用你当前正在调用的id
(我假设是特定游戏的ID)来指示哪些玩家一起去。
看起来像这样:
game_id | player_num | player_name | score
1 | 1 | Octern | 100
1 | 2 | Boris | 400
1 | 3 | Jarlsberg | 300
1 | 4 | Pete | 40000
...
然后,为了找到给定游戏的高分(在这种情况下,游戏#1),你会说:
select player_name from scores
WHERE game_id = 1
ORDER BY score desc
LIMIT 1