从Left Outer Join返回唯一行

时间:2013-09-07 03:44:38

标签: sql outer-join

我正在尝试构建一个查询,它将为我提供唯一的行。细节: -

Table 1 (F1, F2 are the columns)
F1  F2
1   A1
2   A2
3   A3
4   A4

Table 2 (F3,F4 are the columns)
F3  F4
1   B1
1   B11
2   B2
2   B22

我的查询(不正确)
选择rrn(A),F1,F2,F3,F4来自rush2hem1.T1 A左外连接rush2hem1.T2 B on A.F1 = B.F3

这给了我以下输出,这不是我想要的: -

RRN F1  F2  F3  F4
1   1   A1 1    B1 
1   1   A1 1    B11 
2   2   A2 2    B2 
2   2   A2 2    B22 
3   3   A3 (null)   (null)
4   4   A4 (null)   (null)

我正在构建查询的预期输出是: -

RRN F1  F2  F3  F4
1   1   A1 1    B1 
2   2   A2 2    B2 
3   3   A3 (null)   (null)
4   4   A4 (null)   (null)

如果您有任何建议,请与我们联系。

3 个答案:

答案 0 :(得分:2)

这个问题可以在不同的RDBMS中以不同的方式解决。在任何情况下,您都必须指定要从Table2获取哪一条记录(通过order by子句)

如果您的数据库具有窗口函数row_number(),您可以像这样使用它:

select
    F1, F2, F3, F4
from (
    select
        T1.F1, T1.F2, T2.F3, T2.F4,
        -- order by specifying which row you would get from Table2
        row_number() over(partition by T1.F1 order by T2.F4) as rn
    from Table1 as T1
        left outer join Table2 as T2 on T2.F3 = T1.F1
) as cte  
where rn = 1;

在SQL Server中,您可以使用outer apply

select
    T1.F1, T1.F2, T2.F3, T2.F4
from Table1 as T1
    outer apply (
        select top 1 T2.F3, T2.F4
        from Table2 as T2
        where T2.F3 = T1.F1
        order by T2.F3 asc   -- This is important line
    ) as T2;

在PostgreSQL中,您可以使用distinct on语法:

select distinct on (T1.F1)
    T1.F1, T1.F2, T2.F3, T2.F4
from Table1 as T1
    left outer join Table2 as T2 on T2.F3 = T1.F1
order by T1.F1, T2.F4; -- sort by F4 is important

答案 1 :(得分:1)

未经测试,这是SQL服务器版本。

select rrn(A), F1,F2,F3,F4
from
(
 select rrn(A), F1,F2,F3,F4,row_number() over(partition by RRN order by RRN) as rn
from rush2hem1.T1 A left outer join rush2hem1.T2 B 
on A.F1=B.F3
) as dt
where dt.rn = 1

答案 2 :(得分:0)

请使用OUTER APPLY

检查结果
SELECT 
    * 
FROM 
    Table1 a
OUTER APPLY 
    (SELECT 
        TOP 1 * 
    FROM 
        Table2 b 
    WHERE a.F1=b.F3)c