Let’s say I have a table that has 3 fields: (id, name, points
).
Now initially I want to order them by points and also get the position. So here’s my current query that does this:
SELECT
id,
name,
points,
ROW_NUMBER() OVER (ORDER BY points DESC) AS position
FROM
mytable;
This now works, and I get the following result set:
Here’s where it gets tricky. Let’s say I’m interested in specific row. For example I am interested in EnglishRose
. I would love to know what position it has based on the points.
I can’t just return the whole set and then iterate until I find this row because this table is massive (let’s say we are talking about 100,000+ records. I am trying to find most optimal solution for this. Any ideas? Keep in mind any solution that is working should hopefully also be optimal. I am asking because probably some non optimal sub selects can be done
Any ideas by MySQL experts? Btw my mysql version is >8
3
Answers
If you know the specific element by name that you want to isolate you can use the WHERE statement like so:
WHERE (name = ‘EnglishRose’)
(Im not to sure if this is 100% correct since its been a while since i wrote SQL :-))
I hope this helps!
Have a look at CTE : https://dev.mysql.com/doc/refman/8.0/en/with.html
They allow you to treat a query as a local table.
You could do something like
The records will not all be scanned, but only the ones with points that are higher than the one you’re looking for:
Demo here