简体   繁体   中英

MySQL: Conditional MIN() with GROUP BY

I have this table called times where I record race information for a racing game:

race_id     map     name    time
30509       desert  Peter   12.68
30510       desert  Jakob   10.72
30511       desert  Peter   18.4
30512       jungle  Peter   39.909
30513       jungle  Peter   39.84
30514       desert  Harry   16.129
30515       space   Harry   774.765
30516       jungle  Jonas   46.047
30517       city    Jonas   23.54
30518       city    Jonas   23.13
30519       desert  Mike    22.9
30520       space   Fred    174.244

I have two questions. How would I best go about:

  1. Finding the lowest time (world record) on a given map?

I have tried this query:

SELECT *, MIN(time) FROM times WHERE map = 'desert';

This yields a seemingly incorrect arbitrary row with an added column called MIN(time) where the correct lowest time is.

  1. Finding the lowest time on all maps, but only if it's done by a certain player (find all world records by given player)?

For this I have tried this query:

SELECT *, MIN(time) FROM times WHERE name = 'Peter' GROUP BY map;

This seems to only return the first row by the given name for each map, regardless if it's the lowest time or not.

I'm fairly new to SQL(MySQL), so I might be missing something obvious here. I've been looking around for quite a while now, and any help would be greatly appreciated. Thanks!

if you want the fastest performance on a given race, you can just order by and limit :

select *
from times
where map = 'desert'
order by time limit 1

On the other hand, if you want all race records for a given user, then it is a bit different. One option uses a correlated subquery for filtering:

select t.*
from times t
where 
    name = 'Peter' 
    and time = (select min(t1.time) from times t1 where t1.map = t.map)

Finding the lowest time (world record) on a given map

SELECT `time`
FROM times
WHERE map = @map
ORDER BY `time` ASC 
LIMIT 1

Finding the lowest time on all maps, but only if it's done by a certain player (find all world records by given player)

SELECT `time`
FROM times
WHERE name = @name
ORDER BY `time` ASC 
LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM