SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

前端 未结 10 1551
星月不相逢
星月不相逢 2020-11-28 18:38

What is the difference between CROSS JOIN and FULL OUTER JOIN in SQL Server?

Are they the same, or not? Please explain. When would one use either of these?

10条回答
  •  借酒劲吻你
    2020-11-28 19:31

    They are the same concepts, apart from the NULL value returned.

    See below:

    declare @table1 table( col1 int, col2 int );
    insert into @table1 select 1, 11 union all select 2, 22;
    
    declare @table2 table ( col1 int, col2 int );
    insert into @table2 select 10, 101 union all select 2, 202;
    
    select
        t1.*,
        t2.*
    from @table1 t1
    full outer join @table2 t2 on t1.col1 = t2.col1
    order by t1.col1, t2.col1;
    
    /* full outer join
    col1        col2        col1        col2
    ----------- ----------- ----------- -----------
    NULL        NULL        10          101
    1           11          NULL        NULL
    2           22          2           202
    */
    
    select
        t1.*,
        t2.*
    from @table1 t1
    cross join @table2 t2
    order by t1.col1, t2.col1;
    
    /* cross join
    col1        col2        col1        col2
    ----------- ----------- ----------- -----------
    1           11          2           202
    1           11          10          101
    2           22          2           202
    2           22          10          101
    */
    

提交回复
热议问题