连接的T-SQL问题

时间:2015-03-05 18:56:19

标签: sql sql-server tsql join

我正在尝试从两个数据集中获得帖子末尾的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

2 个答案:

答案 0 :(得分:2)

改为使用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);

答案 1 :(得分:0)

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

Sintax:

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

我希望它有所帮助!