首页 文章

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

提问于
浏览
1

我有两张表如下

table1

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

table2

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 回答

  • 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记录 .

相关问题