2013-04-26 36 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子句中使用它。