我每次发生时都会报告用户的分数。现在我想显示用户的最高分。表格设置如下:
玩家(身份证,姓名)
PlayerHasAchievement(id,playerId, achievementId)
成就(身份,类型,金额,时间)
这就是我现在所拥有的:
$query = "SELECT MAX(ach.amount) as amount, p.username, ach.time
FROM achievement as ach
INNER JOIN playerHasAchievement as playAch ON ach.id = playAch.id
INNER JOIN player as p ON p.userId = playAch.userid
WHERE ach.type = 2
GROUP BY amount
ORDER by `amount` DESC
LIMIT $amount";
我试图明确地选择它但它不起作用。我很难过,它应该很容易!感谢您的阅读,我将不胜感激任何帮助!
答案 0 :(得分:5)
问题是您获得的ach.time
与MAX(amount)
的行不同。加入另一个子查询以首先获得MAX(amount)
。
注意:在您发布的表格定义中,playerHasAchievement
有一个字段playerId
而不是userId
SELECT MAX(ach.amount) as amount, p.username, MAX(ach.time) MaxTime
FROM achievement as ach
INNER JOIN playerHasAchievement as playAch ON ach.id = playAch.id
INNER JOIN player as p ON p.userId = playAch.playerId
INNER JOIN (
SELECT playAch.playerId, MAX(ach.amount) as MaxAmount
FROM achievement as ach
INNER JOIN playerHasAchievement as playAch ON ach.id = playAch.id
WHERE ach.type = 2
GROUP BY playAch.playerId
) g ON p.playerId = g.playerId AND ach.amount = g.MaxAmount
WHERE ach.type = 2
GROUP BY p.playerId
ORDER by `amount` DESC
LIMIT $amount";
我们将外部查询分组的原因是为了避免关系 - 比如一个玩家两次得分相同。
答案 1 :(得分:2)
在第3行的加入中,你真的不想要
INNER JOIN playerHasAchievement as playAch ON ach.id = playAch.achievementId
和其他人都是正确的,您需要按非聚合列进行分组,而不是聚合列。
假设您的数据库布局与问题中指定的一样,那就是我将使用的查询。
SELECT ach.amount, p.Name, ach.time
FROM achievement as ach
JOIN playerHasAchievement as playAch ON ach.id=playAch.achievementId
JOIN player AS p ON p.id = playAch.playerId
WHERE ach.type = 2
AND ach.amount = (SELECT MAX(ach.amount)
FROM achievement as ach
JOIN playerHasAchievement as playAch ON ach.id=playAch.achievementId
JOIN player AS p ON p.id = playAch.playerId
WHERE ach.type = 2)
GROUP BY ach.amount
ORDER by ach.time
取第一个结果(如果有相同分数的倍数)将给你高分和最低时间。
希望有所帮助!
答案 2 :(得分:1)
您没有正确使用群组,因为您只是按金额分组。 用户名和时间怎么样?