简体   繁体   中英

Select global min() in a new column for all rows

I have a table db_race

--------------------------
| Name    | Time | Map   |
--------------------------
| Max     | 240  | test1 |
| Alvin   | 600  | test2 |
| Amanda  | 234  | test1 |
| Angela  | 50   | test1 |
| Angela  | 2000 | test1 |
--------------------------

I now want to select some rows ordered by best Time on a map like the following

SELECT Name, min(Time) AS Time 
FROM db_race 
WHERE Map='test1' 
GROUP BY Name 
ORDER BY Time ASC

That works perfectly fine, but I want to have the best time of all records added to another column looking like the following. (will later work with that but thats not a part of the question)

----------------------------
| Name    | Time | TopTime |
----------------------------
| Angela  | 50   | 50      |
| Amanda  | 234  | 50      |
| Max     | 240  | 50      |
----------------------------

So far I tried the following but it only shows the best time, I want it for the whole selected table

SELECT *, min(Time) AS TopTime 
FROM (SELECT Name, min(Time) AS Time 
      FROM db_race 
      WHERE Map='test1' 
      GROUP BY Name 
      ORDER BY Time ASC) a

I want to make sure I dont need to find the TopTime by using a subquery. The actual query will be very long and my goal is to not have it executed twice.

Something like this, perhaps?

SELECT 
    Name, 
    min(Time) as Time, 
    (SELECT min(Time) FROM db_race WHERE Map='test1') as TopTime
FROM db_race
WHERE Map='test1'
GROUP BY Name
ORDER BY Time

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