tags:

views:

45

answers:

3

I need a query that will fetch a single item before a certain Id and an item after that same Id.

For example I have five rows, id's 1 to 5 and i need to select id before and after id 3, so that I get 2 and 4 as a results.

Is there a way to do it with a single query?

Edit:

I forgot to tell that maybe results would not be siblings but next sibling that matches criteria:

SELECT routeId FROM routes WHERE routeId>::p0:: AND assetKmId<>'0'

so next or previous sibling should match assetKmId<>'0' (this routeId>::p0:: is ofcourse not valid in this scenario)

A: 

Wouldn't this work?

SELECT * FROM :tablename
WHERE id = :yourid - 1 OR id = :yourid + 1

Of course, you should set the table name and id parameters in your query.

Tamás Mezei
see edit, sorry I didn't explain it further
dfilkovi
ah, so you want the closest before and after that matches the other criteria
Tamás Mezei
yes, that's right
dfilkovi
+1  A: 

Why not use max,min and union results

SELECT min(routeId) FROM routes WHERE routeId>::p0:: AND assetKmId<>'0' 
UNION 
SELECT max(routeId) FROM routes WHERE routeId<::p0:: AND assetKmId<>'0'
solomongaby
A: 

Refining solomongaby's solution to return complete records instead of only the IDs (just in case that is of any use to you):

SELECT * 
  FROM routes 
 WHERE routeId = (select min(routeId) from routes where routeId >::p0::)
   AND assetKmId <> '0' 
UNION 
SELECT *
  FROM routes 
 WHERE routeId = (select max(routeId) from routes where routeId<::p0::) 
   AND assetKmId<>'0'
Tom Bartel