选择一对多关系中的一行

时间:2016-01-06 05:08:22

标签: sql oracle

我有一对多的关系。

Table 1: C_Id, Name
Table 2: Id, Name

我想从表2中为表C_Id中的每个Id选择一行。

示例:

Table 1
             1    First Row
             2    Second Row

Table 2
             1    First Row 1
             1    First Row 2
             2    Second Row 1
             2    Second Row 2

我的查询结果是:

 1    First Row 1 (First row for ID 1)

 2    Second Row 1 (First row for ID 2)

我需要什么查询来获取此信息?

3 个答案:

答案 0 :(得分:0)

SELECT t1.C_Id, MIN(t2.Name) -- or MAX, depending on your needs
FROM t1 INNER JOIN t2 ON (t1.C_Id = t2.Id)
GROUP BY t1.C_Id

答案 1 :(得分:0)

从tab1,tab2中选择*,其中tab1.c_id = tab2.id和rownum = 1; - 如果你想对ace或desc进行排序,请按顺序使用。

答案 2 :(得分:0)

如果您可以依赖表2的ID,那么这很简单:

select t1.c_id 
       , t1.name
       , t2.id as t2_id
from t1
     join t2 on t1.name = t2.name
where t2.id = 1;

但我怀疑你的实际案例更复杂。但是可以使用ROW_NUMBER()分析函数轻松解决:

select c_id
       , name
       , t2_id
from (
    select t1.c_id 
           , t1.name
           , t2.id as t2_id
           , row_number() over ( partition by t1.name
                           order by t2.id asc ) rn 
    from t1
         join t2 on t1.name = t2.name
)
where rn = 1;