I have a table holding entries which can be sorted by rank. I want to get the top 10 entries (which is simple using SELECT * FROM table ORDER BY rank DESC
), but then I want those entries in descending order, so the one with the lowest rank ends up at the top. How would I do this?
views:
61answers:
2
+3
A:
You should be able to do:
SELECT *
FROM (SELECT * FROM `table` ORDER BY rank DESC LIMIT 10) dt
ORDER BY dt.rank ASC;
I guess you have a table like this:
CREATE TABLE `table` (id int, rank int);
INSERT INTO `table` VALUES (1, 20), (2, 19), (3, 18), (4, 17), (5, 16), (6, 15),
(7, 14), (8, 13), (9, 12), (10, 11), (11, 10),
(12, 9), (13, 8), (14, 7), (15, 6), (16, 5), (17, 4),
(18, 3), (19, 2), (20, 1);
You would get a result like this:
+------+------+
| id | rank |
+------+------+
| 10 | 11 |
| 9 | 12 |
| 8 | 13 |
| 7 | 14 |
| 6 | 15 |
| 5 | 16 |
| 4 | 17 |
| 3 | 18 |
| 2 | 19 |
| 1 | 20 |
+------+------+
10 rows in set (0.02 sec)
UPDATE:
@onik's solution returns the same result.
Daniel Vassallo
2010-08-30 09:49:05
+5
A:
(SELECT * FROM table ORDER BY rank DESC LIMIT 10) ORDER BY rank ASC;
Is this what you're looking for?
onik
2010-08-30 09:52:23
@Martin: It appears to work fine in MySQL (as long as `table` is enclosed in backticks)... I didn't know it was possible either :)
Daniel Vassallo
2010-08-30 09:56:51
@onik - +1 And my apologies, @Daniel - Thanks for letting me know!
Martin Smith
2010-08-30 10:04:07