具有多个记录的表上的内连接

时间:2012-11-03 14:16:11

标签: sql oracle oracle11g top-n

我有两张表如下

表1

column1|column2
----------------
a1     | c1
----------------
a2     | c2

表2

column1|column2|column3
----------------------
1      | a1    | x
-----------------------
2      | a1    | y
-----------------------
3      | a1    | z
-----------------------
4      | a2    | ab
-----------------------
5      | a2    | cd
-----------------------
6      | a2    | ef

Table1是父表,table2是子表。

table1的column1映射到table2的column2。

Table2可以包含table1中column1的每个条目的多个记录。有些事情就像这样。

我想将table1连接到table2,但我只想要table2的所有条目的第一条记录。

所以我的结果集将是

column1|column2|column3
----------------------
1      | a1    | x
-----------------------
2      | a2    | ab

如何在oracle 11 g中实现连接。我使用sql navigator +

1 个答案:

答案 0 :(得分:1)

select
  x.column1,
  x.column2,
  x.column3
from
    (select
      t2.column1,
      t2.column2,
      t2.column3,
      dense_rank() over (partition by t2.column1, t2.column2 order by t2.column3) as rank
    from
      table1 t1
      inner join table2 t2 on t2.column2 = t1.column1) x
where
  x.rank = 1

但是由于你没有使用t1中的任何字段,你可以省略连接。它可以用于过滤(也可以通过使用exists来完成,但由于t1是父表,所以t2中的所有记录都应该具有匹配的t1记录。