select 10 rows before and after one row

Hi,
I have a little question. I would like to do a select query and get few rows before and after the row I’m looking for. For example, if I had products list with thousand of products, and I’m searching for a product A, I would like the code to show the product A in the middle with price P, then few products more expensive (the next in order) and few cheaper ones. Is it somehow easily possible?
Thanks in advance
Asaru

Shouldn’t be too difficult but it’s going to depend a lot on how your tables are set up.

You’d have a query to get the primary record you’re looking for. Save the results in an array.
Second query to get the previous 5 (or whatever) rows using a where clause with a marker from the previous query (cost or whatever you have)

select * from products where cost > xxx and cost < xxx limit 5

Then a third query similar to the second. Again with the where clause

select * from products where cost > xxx and cost < xxx limit 5

Now you’ll have 3 arrays… 1 for the data that was searched for, 1 for the next cheaper 5 items, 1 for the next 5 more expensive ones.

Output data as you see fit.

Thanks for response
I was just wondering, if this way’ll be fast enough, if there were e.g. few thousands of rows, to not make it too slow.
Asaru

Yeah… I was kind of wondering that myself. But a few 1000 rows, even 10000 rows is really nothing for even a low-end DB server. Really depends on how often the query will run… couple times an hour or couple times a second?

Well, I was thinking of running it quite often. But I also just came to an idea, because if the infos there didn’t need to be exactly actual, that I could do kind of “sort” query, let’s say once in a hour, which could select ordered by price and update the “position” field in DB, and then select based on the position field.

Sponsor our Newsletter | Privacy Policy | Terms of Service