1

I'm using a SQL-statement to retrieve the top 5 entries in a list:

SELECT ... FROM table ORDER BY someColumn DESC LIMIT 5

The result will look something like this:

Name       Count
Person B   10
Person D   8
Person A   5
Person E   5
Person C   4

If there are more results with a value like the fifth entry in the list (4 in the example), I would like to show them too. Is there a way to achieve this with a single query?

So let's say the complete lists looks like this:

Name       Count
Person B   10
Person D   8
Person A   5
Person E   5
Person C   4
Person H   4
Person I   4
------------
Person G   3
Person F   1
Person J   1

How can I modify my query to return the first seven results? Obviosuly I can't use LIMIT 7 or WHERE Count >= 4, as I don't know that in advance.

4
  • how come you can't use LIMIT 7? Use LIMIT 100 Commented Jun 2, 2011 at 6:55
  • What happens when your data is 10, 10, 10, 10, 10, 10, 10, 5, 4, 3, 2, 1? Will you show the 7 rows with count = 10? Or 7 rows with count = 10 + 4 rows with count between 5 and 2? Commented Jun 2, 2011 at 7:11
  • @Salman: The description is clear. It will show the seven 10 s. Notice the two 5, 5 in the question. Commented Jun 2, 2011 at 7:16
  • @yper: In that case you get +1 :) Commented Jun 2, 2011 at 7:19

2 Answers 2

5

You mean you want the fist five results but also all other results which are tied in 5th place, right? One solution is to get the 5th result first - using a subquery - and then get what you need:

SELECT ...
FROM table
WHERE someColumn >=
    ( SELECT someColumn 
      FROM table 
      ORDER BY someColumn DESC 
      LIMIT 4, 1                      <-- only the 5th 
    )
ORDER BY someColumn DESC 
Sign up to request clarification or add additional context in comments.

Comments

0

Two solutions:

Sol 1: Use LIMIT 100 or so, and eliminate unwanted rows in your program.

Sol 2: Execute two queries, most probaby that will be more costly:

SELECT * FROM (SELECT ... FROM table ORDER BY
  someColumn DESC LIMIT 5) 
  UNION (SELECT ... FROM table ORDER BY
         someColumn DESC LIMIT 50, 5);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.