mySQL - Obtain only users from a table with max points
I need to obtain n users from a table with the max points.
Table
id name points
1 pep 4
2 roky 5
3 jhon 2
4 sant 5
The query result will be 'roky' and 'sant开发者_运维知识库'.
I have used a subquery like this
SELECT name FROM table
WHERE points = (SELECT MAX(points) FROM table)
Is it possible to do with only one query (no sub-queries and no joins)?
You're pretty much on the right track. It needs a subquery of some sort.
See here to see how the MySQL manual does it.
I'm really not sure if this could work. Select the max points from the table, then join itself using the points number. It could potentially display the needed names without a subquery. But of course, the subquery is the better (and faster) answer.
SELECT max(t1.points) as maxpoints, t2.name FROM table t1
INNER JOIN table t2 on t2.points = maxpoints
Edit: Wait, what? No joins? Since when was this part of the task? Okay, my solution was outdated while writing it. Oh well.
Sort the result by row and get the first one.
SELEC name FROM table
ORDER BY points DESC
LIMIT 1
精彩评论