在尝试分组时查询选择错误的数据

时间:2015-04-08 06:58:23

标签: mysql sql select group-by

这个 MySQL 查询应该返回今天得分低于270的TOP 15玩家。每个玩家可以玩多次,所以它应该返回玩家的最高分。我无法理解GROUP BYSELECT条款的错误。

SELECT userName, 
       MAX(CAST(Score AS UNSIGNED)) Score
FROM Game 
WHERE userName IS NOT NULL AND 
      CAST(Score AS UNSIGNED) < 270 AND 
      DATE(PlayTime) = DATE(NOW())
GROUP BY FBId, userName, CAST(Score AS UNSIGNED)
ORDER BY CAST(Score AS UNSIGNED) DESC LIMIT 15

FBId对于每个玩家来说都是独一无二的,这就是为什么我在GROUP BY条款中取消它,userName如果玩家具有相同的名称,则VARCHAR可以相等。

P.S。分数属于INT类型,这就是我将其投放到Will Jason 227 Will Jason 226 Jessica Anton 219 Jessica Anton 218 Tom Edi 215 Simon Dougs 213 Peter Yang 210 Steeve Maclay 208 Monica Termson 207 Dave Stuart 206 的原因。

使用上面的查询后,在下面选择重复的名称:

Score

那是因为包含GROUP BYCAST(Score AS UNSIGNED)条款?


但如果我使用以下查询(从GROUP BY中移除SELECT userName, MAX(CAST(Score AS UNSIGNED)) Score FROM Game WHERE userName IS NOT NULL AND CAST(Score AS UNSIGNED) < 270 AND DATE(PlayTime) = DATE(NOW()) GROUP BY FBId, userName ORDER BY CAST(Score AS UNSIGNED) DESC LIMIT 15 ):

Will Jason          227
Jessica Anton       219
Jeniffer Taylor     195
Tom Drugton         187
Monica Termson      207
Christina Queenton  183
Dave Stuart         206
David Tomson        170
Susan Clark         205
Sarah Lopez         188

选择也错了(跳过一些用户):

Id INT AUTO_INCREMENT
FBId INT
Score VARCHAR(20)
userName NVARCHAR(80)
PlayTime TIMESTAMP

你有什么想法吗?似乎第一个查询只是使用重复的名称选择正确的值。

更新

表格结构:

{{1}}

1 个答案:

答案 0 :(得分:1)

select fbid, username, max(score) as thescore
  from game
    where score < 270
  group by fbid
  order by max(cast(score as unsigned)) desc limit 15;

演示:http://sqlfiddle.com/#!9/3e2bc/9