通过两列同等重要的顺序排列MySQL表

时间:2012-03-01 14:08:49

标签: mysql

我有一个双人游戏,在桌子上存储分数。

我想从表中选择高分,这是我目前的代码:

SELECT * FROM games ORDER BY GREATEST(player1Score,player2Score) DESC LIMIT 10

问题是它只返回每一行的一个实例,即使例如第1行中两个分数中的较低者保证包含在前10行中。

3 个答案:

答案 0 :(得分:2)

使用UNION ALL

SELECT col1, col2, col3, player1Score AS score FROM games
UNION ALL
SELECT col1, col2, col3, player2Score AS score FROM games
ORDER BY score DESC
LIMIT 10

另外,请勿使用SELECT *。明确列出列。

答案 1 :(得分:0)

( SELECT *, player1Score as score
  FROM games 
  ORDER BY score DESC 
  LIMIT 10
)
UNION ALL
( SELECT *, player2Score AS score 
  FROM games 
  ORDER BY score DESC 
  LIMIT 10
)
ORDER BY score DESC
LIMIT 10

答案 2 :(得分:0)

创建一个播放器表和一个连接表可能会更好(即使只有两个用户)。然后,您可以轻松创建一个查询来执行您要执行的操作。当然,更改更新/保存功能以匹配新架构需要一点点。

players
-----
playerId
playerName

joinPlayerGame
-----
joinId
playerId
gameId

games
-----
modify the player score fields to just be 'score'

SELECT g.*, p.playerName FROM players p INNER JOIN joinPlayerGame j ON j.playerId = p.playerId INNER JOIN games g ON g.<whatever your key is> = j.gameId ORDER BY g.score DESC LIMIT 10

我希望有所帮助,祝你好运!