1

For the last two days, I have been asking questions on rank queries in Mysql. So far, I have working queries for

  1. query all the rows from a table and order by their rank.
  2. query ONLY one row with its rank

Here is a link for my question from last night

How to get a row rank?

As you might notice, btilly's query is pretty fast.

Here is a query for getting ONLY one row with its rank that I made based on btilly's query.

set @points = -1; 
set @num = 0;

select * from (

SELECT id
  , points
  , @num := if(@points = points, @num, @num + 1) as point_rank
  , @points := points as dummy
FROM points
ORDER BY points desc, id asc

) as test where test.id = 3

the above query is using subquery..so..I am worrying about the performance.

are there any other faster queries that I can use?

Table points

id      points
1   50
2   50
3   40
4   30
5   30
6   20
Community
  • 1
  • 1
Moon
  • 22,195
  • 68
  • 188
  • 269

1 Answers1

2

Don't get into a panic about subqueries. Subqueries aren't always slow - only in some situations. The problem with your query is that it requires a full scan.

Here's an alternative that should be faster:

SELECT COUNT(DISTINCT points) + 1
FROM points
WHERE points > (SELECT points FROM points WHERE id = 3)

Add an index on id (I'm guessing that you probably you want a primary key here) and another index on points to make this query perform efficiently.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • // Thank you for the input. I just added a sample table with 6 rows. Your query works fine for id #1,2, but I get a different result with id #3. I am expecting 2 as the result, but I get 3. How do I get 2 instead of 3 for id #3? I am getting 3 because there are two records (#1 and #2) that have higher values than #3. – Moon Mar 19 '11 at 09:10
  • @Moon: To fix that change `COUNT(*)` to `COUNT(DISTINCT points)`. See update. – Mark Byers Mar 19 '11 at 09:13
  • // Finally!!! I really appreciate your help!!!! Have a great weekend! (I will with your help!!) – Moon Mar 19 '11 at 09:15
  • GREAT JOB! Your solution for what I'm doing is taking 0.053s compared to 1.652s using mariadb's row_number() window function – xer21 Dec 06 '19 at 11:43