If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > N records above/below the selected record.

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-02-10, 08:16
andy982183 andy982183 is offline
Registered User
 
Join Date: Mar 2010
Posts: 18
Question N records above/below the selected record.

Hii,

Is there a way to fetch 'n' number of records above or below the selected record.

example:
SELECT NAME FROM MyTable
WHERE NAME LIKE 'Andy'


Here the query output will be 'Andy'
So I require 'n' number of records to be displayed above or below 'Andy'

Kindly Advice
Thanks

Last edited by andy982183; 04-02-10 at 08:23.
Reply With Quote
  #2 (permalink)  
Old 04-02-10, 08:35
mike_bike_kite mike_bike_kite is offline
vaguely human
 
Join Date: Jun 2007
Location: London
Posts: 2,519
Quote:
Originally Posted by andy982183
Is there a way to fetch 'n' number of records above or below the selected record.
You want to look at adding an order by clause and a limit clause to your select statement.
__________________
Mike
Reply With Quote
  #3 (permalink)  
Old 04-02-10, 11:02
Ikviens Ikviens is offline
Registered User
 
Join Date: Mar 2006
Posts: 55
Hi,
Code:
SELECT M1.name, COUNT(*)
  FROM MyTable M1 INNER JOIN MyTable M2
    ON M1.name >= M2.name
 GROUP BY M1.name
HAVING COUNT(*) <= (SELECT COUNT(*)
                      FROM MyTable M3
                     WHERE M3.name <= 'Andy');
This retrieves the results you want, although I am not sure how costly it gets as your table grow (in other words, as you collect more data in there).

Edit:
Changing the predicate in the HAVING clause to >=, you will get records of Andy and below.
If there are records where the name column is NULL, they are not counted in the ordering.

Last edited by Ikviens; 04-02-10 at 11:46. Reason: edit
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On