tags:

views:

116

answers:

5

Hi guys!

I've a query like this:

select t1.id, t1.sample, t2.id from table t1 join table t2  
on t1.sample = t2.sample and t2.id > t1.id

I need to get the first row that satisfy the second condition.

Any idea?

+2  A: 

Well.

You could try this: if you're working with SQL Server, add a top 1

if you're working with MySQL, add a limit 1

it will only return the first row.

To ensure, you can add an order clause too.

Kico Lobo
He is using an Oracle DB.
Dougman
+2  A: 
SELECT t1.id, t1.sample, t2.id FROM table t1 JOIN TABLE t2
ON t1.sample = t2.sample AND t2.id > t1.id WHERE ROWNUM = 1
Bertrand Marron
There's a catch to this technique. If the SELECT contains an ORDER BY clause, then WHERE ROWNUM = 1 will execute before the ORDER BY. In this case, put the whole SELECT (minus the WHERE ROWNUM = 1 condition) in a subquery, then SELECT * FROM (your subquery) WHERE ROWNUM = 1. Yes, it's convoluted, but so is Oracle sometimes.
Cylon Cat
with rownum = 1 works but I need to extract all id and not one only.
Andrea Girardi
Didn't you say that you wanted to get the first row satisfying your condition?
Bertrand Marron
+1  A: 

All rows returned will satisfy both conditions, so you don't have to do anything special to make sure that the second condition is satisfied.

If you want to limit the returned results size to 1, append WHERE ROWNUM = 1 to the query if it will be run on Oracle.

Ryan Ahearn
Yes, but for all id I've to take the first id that satisfy > condition, with rownum = 1 only the first row is returned.
Andrea Girardi
I'm not sure I understand the problem; all ids returned will satisfy the > condition. Are you looking for the largest t2.id in addition to t2.id > t1.id?
Ryan Ahearn
A: 

Oracle uses something called "ROWNUM". Limiting the number of results is annoyingly inconsistent across DBMSs.

SELECT t1.id, t1.sample, t2.id
FROM table t1 join table t2  
ON t1.sample = t2.sample and t2.id > t1.id
WHERE ROWNUM <= 1
ctford
A: 

If you want the least t2.id that satisfies the second condition then

select * from (select t1.id, t1.sample, t2.id from table t1 join table t2
on t1.sample = t2.sample and t2.id > t1.id order by t2.id ) where rownum =1

If you want the greatest t2.id that satisfies the second condition then

select * from (select t1.id, t1.sample, t2.id from table t1 join table t2
on t1.sample = t2.sample and t2.id > t1.id order by t2.id desc) where rownum =1

Dinesh Bhat