I am using phpMyAdmin on MySQL 5.7
The code below selects the lowest values excluding any zero values and gives me a nice table of all the teamids with the lowest times in seconds next to them for that event (zid).
SELECT teamid, MIN(time) AS 'fastest time'
FROM data
WHERE time > 0 AND zid = 217456
GROUP BY teamid
How do I adapt it to get the 4th lowest values?
I have tried countless suggestions found via searching but none work
Table Headings:
id (AI column set as Primary Index)
zid (this is an event identification number)
teamid
name
time (given in seconds)
I could add a position in team column which would make this very easy? Then I just ask MySQL to get me all the positions = to 4 ?
3
Answers
If your version supports window-functions (since 8.0):
EDIT:
dense_rank
seems to fit better, it will give the fourth-best time now, ignoring multiple appearances of the best to third-best times. The earlier version usedrow_number
, not ignoring multiple apperances. Thanks for mentioning in the comments.Since your version does not support window-functions, you can use a subselect with a
LIMIT
(I assume you have a fieldid
, that is a primary key. If your primary key is another field, just replace this. If there is more than one field in your primary key, you will need to check all of them):MySQL 8: Use Window functions.
Mysql 5.7 and Lower: We will use following variables to calculate this on the sorted data(teamid and then time)
rank
– to set rank for each unique(teamid, time)c_time
– whenever there is a change betweentime
of two consecutive rows, we will increase the rank.IF(@c_time = d.time, @rank, @rank:= @rank + 1)
c_team_id
– we will check whether two consecutive rows have same or different team, if different then reset rank to 1. Check else part IF(@c_team_id = d.teamid, …,@rank:= 1
)