T-SQL 连接问题

T-SQL Issue with joins

我正在尝试从两个数据集中实现 post 末尾的 Expected Result。我正在使用 left join 这并不能帮助我获得预期的结果。我想从两个表中获取所有匹配和不匹配的记录。

用于创建和检索数据集的查询以及我当前的结果集如下:

select 
    a.id, a.name, a.rev, isnull(b.conv, 0) as conv 
from 
    (select 
        1 as id, 'A' as name, 2 as rev, 0 as conv

     union all

     select 
        2 as id, 'B' as name, 1 as rev, 0 as conv) a
left join
    (select 
         1 as id, 'A' as name, 0 AS rev, 2 as conv

     union all

     select 
         3 as id, 'C' as name, 0 as rev, 3 as conv) b on a.id = b.id

以上查询使用左连接的当前结果:

id  name    rev conv
---------------------    
1   A        2   2
2   B        1   0

预期结果:

id  name    rev conv
--------------------
1   A        2    2
2   B        1    0
3   C        0    3

改用FULL JOIN

SELECT  ISNULL(a.id,b.id) id,
        ISNULL(a.name,b.name) name, 
        ISNULL(a.rev,0) rev, 
        ISNULL(b.conv,0) conv 
FROM (  SELECT 1 as id , 'A' as name , 2 as rev, 0 as conv
        UNION ALL
        SELECT 2 as id , 'B' as name, 1 as rev, 0 as conv) a
FULL JOIN ( SELECT 1 as id , 'A' as name, 0 AS rev, 2 as conv
            UNION ALL
            SELECT 3 as id , 'C' as name, 0 as rev, 3 as conv) b
    ON a.id = b.id
ORDER BY ISNULL(a.id,b.id);

您应该尝试使用 FULL OUTER JOIN,它结合了 LEFT 和 RIGHT 联接的结果。

语法:

SELECT column_name(s)
FROM 
     table1 FULL OUTER JOIN table2
ON 
     table1.column_name = table2.column_name;

希望对您有所帮助!