Created
February 12, 2012 20:31
-
-
Save abedsujan/1810735 to your computer and use it in GitHub Desktop.
MySQL::Select the Nth Highest Record in a Database Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Step: MySQL provides LIMIT clause so we just have to leverage it to rewrite the query as follows | |
SELECT * | |
FROM table_name | |
ORDER BY column_name DESC | |
LIMIT n - 1, 1 | |
Step :Query to get the nth highest record | |
SELECT * | |
FROM ( | |
SELECT * | |
FROM table_name | |
ORDER BY column_name ASC | |
LIMIT n | |
) AS tbl | |
ORDER BY column_name DESC | |
LIMIT 1 | |
Step: Using Sub-Query | |
SELECT * | |
FROM table_name AS a | |
WHERE n - 1 = ( | |
SELECT COUNT(primary_key_column) | |
FROM products b | |
WHERE b.column_name > a. column_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment