I want nearest 10 marks for particular student. For example John has marks 73 then i have to find 10 student with marks greater than 73 in ascending order nearest to John. My Table structure is (id,name,marks).
+2
A:
Try this:
SELECT id, name, marks
FROM table1
WHERE marks > (SELECT marks FROM table1 WHERE name = 'John')
ORDER BY marks
LIMIT 10
Mark Byers
2010-04-22 19:32:42
You should use a 1-1 ID comparison instead of [name = 'John'].
Ben
2010-04-22 19:36:04
@Ben: Of course you should, but that's not what he asked for.
Mark Byers
2010-04-22 19:37:58
+2
A:
Select s.id, s.name, s.marks
From students sj
Join students s On ( s.marks > sj.marks )
Where sj.name = 'John'
Order By s.marks
Limit 10
sj
will be student John
(assuming that you have only one John), and s
contains all records with marks greater than John's.
The Limit
limits the output to ten rows.
Peter Lang
2010-04-22 19:33:15
@Mark: Not sure why I thought that would work (not really using MySQL), but since I can't try it right now I removed it. Thanks for the comment, and (+1) for your answer, which is correct too.
Peter Lang
2010-04-22 19:45:00
@Peter Lang: The first value is an offset (zero = no offset). LIMIT 1,10 would cause the first row to be skipped. I don't think that's needed here. See http://dev.mysql.com/doc/refman/5.1/en/select.html
Mark Byers
2010-04-22 19:48:16