开发者

get the first row of a join

开发者 https://www.devze.com 2022-12-13 02:25 出处:网络
I开发者_如何学Python\'ve a query like this: select t1.id, t1.sample, t2.id from table t1 join table t2

I开发者_如何学Python'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?


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


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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消