我设计了一个事件,在该事件中您注册多条鱼,并且我想查询一下以从不同的人中提取前3条最重的鱼。如果是平局,则应由第三个参数决定:谁先注册。我已经测试了在堆栈溢出中发现的几种方法,但是没有一种方法可以满足我的需要。
我的架构如下:
id | playerid | playername | itemid | weight | date | received | isCurrent
位置:
id = PK, AUTO_INCREMENT - it's basically an index
playerid = the unique code of the person who registered the fish
playername = name of the person who registered the fish
itemid = the code of the fish
weight = the weight of the fish
date = pre-defined as CURRENT_TIMESTAMP, the exact time the fish was registered
received = pre-defined as 0, it really don't matter for this analysis
isCurrent = pre-defined as 1, basically every time this event runs it updates this field to 0, meaning the registers don't belong to the current version of the event.
Here you can see the data I'm testing with
我的问题是:如何避免多次为该等级计算相同的玩家编号?
查询1:
SELECT `playerid`, `playername`, `itemid`, `weight`
FROM `event_fishing`
WHERE `isCurrent` = 1 AND `weight` IN (
SELECT * FROM
(SELECT MAX(`weight`) as `fishWeight`
FROM `event_fishing`
WHERE `isCurrent` = 1
GROUP BY `playerid`
LIMIT 3) as t)
ORDER BY `weight` DESC, `date` ASC
LIMIT 3
查询2:
SELECT * FROM `event_fishing`
INNER JOIN
(SELECT playerid, MAX(`weight`) as `fishWeight`
FROM `event_fishing`
WHERE `isCurrent` = 1
GROUP BY `playerid`
LIMIT 3) as t
ON t.playerid = `event_fishing`.playerid AND t.fishWeight = `event_fishing`.weight
WHERE `isCurrent` = 1
ORDER BY weight DESC, date ASC
LIMIT 3
请记住,我必须至少返回以下字段:playerid,playername,itemid,weight,事件的版本必须是实际的(isCurrent = 1),每行一个玩家id,且其注册的权重最大此版本的活动和日期已注册。
我发送的数据的预期输出:
id |playerid|playername|itemid|weight| date |received| isCurrent
7 | 3734 |Mago Xxx | 7963 | 1850 | 2018-07-26 00:17:41 | 0 | 1
14 | 228 |Night Wolf| 7963 | 1750 | 2018-07-26 19:45:49 | 0 | 1
8 | 3646 |Test Spell| 7159 | 1690 | 2018-07-26 01:16:51 | 0 | 1
我得到的输出(带有两个查询):
playerid|playername|itemid|weight
3734 |Mago Xxx | 7963 | 1850
228 |Night Wolf| 7963 | 1750
228 |Night Wolf| 7963 | 1750
感谢您的关注。
编辑:由于我的查询与接受的答案非常相似,因此我遵循了How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?,在评论中我发现乍看上去似乎已经解决了我的问题,但发现了一个接受的答案失败的情况。选中http://sqlfiddle.com/#!9/72aeef/1
如果查看数据,您会发现id 14是1750的第一个输入,因此应该排在第二位,但是MAX(id)返回相同playerid的最后一个输入,因此给我们一个错误的结果。
尽管问题似乎相似,但我的问题更为复杂,因此建议的查询不起作用
编辑2:
我已经设法通过以下查询解决了我的问题: http://sqlfiddle.com/#!9/d711c7/6
但是由于两件事,我将保留这个问题: 1-我不知道这种查询是否会失败 2-尽管我们对第一个查询的限制很多,但我仍然认为可以对其进行优化,因此,我会将其开放给任何可能知道更好方法来解决该问题的人。