2013-04-26 21 views
0

我使用的是Oracle 10,但要問這個問題的最好方法是用示例。加入查詢表引用本身

select * 
    from t1, t2 
where t1.id = t2.id 
    and t1.otherID = (select max(otherID) 
         from t2 
         where id = THE ID FROM THE OUTER QUERY T1 
        ) 

我想你看到我試圖去用這個。我需要在子查詢中引用t1將其加入到最大t2

我需要知道如何創建這樣的查詢。

「來自外部查詢T1的ID」是我的困惑所在。

我試過使用t1.id,但沒有得到結果。

+0

如果此問題不再有效,請刪除它。 – 2013-04-26 21:19:55

回答

0

請嘗試以下

select t1.*, t2.* 
from t1 
join t2 on t1.id = t2.id 
join (select id, max(otherID) as max_otherID 
     from t2 
     group by id 
) a ON a.id = t1.id and a.max_otherID = t1.otherID 

在加入使用子查詢通常提供更好的性能比在where子句中使用它。