SQL Server中的CROSS JOIN和FULL OUTER JOIN的区别是什么?

它们是一样的吗?请解释一下。什么时候使用它们?


当前回答

完全外部连接组合了左外部连接和右外部连接。结果集从满足条件的两个表中返回行,但在不匹配的地方返回空列。

交叉连接是一种笛卡尔积,它不需要任何条件来连接表。结果集包含的行和列是两个表的乘法。

其他回答

交叉连接:交叉连接产生的结果由来自两个或多个表的所有行组合组成。这意味着如果表A有3行,表B有2行,那么CROSS JOIN将导致6行。这两个表之间没有建立任何关系—您实际上只是产生了每一种可能的组合。

Full outer Join:一个Full outer Join既不是“左”也不是“右”——两者都是!它包括参与JOIN的两个表或结果集中的所有行。当JOIN“左侧”的行不存在匹配行时,将看到“右侧”的结果集中的Null值。相反,当JOIN的“右侧”的行不存在匹配行时,将看到“左侧”的结果集中的Null值。

对于SQL Server, CROSS JOIN和FULL OUTER JOIN是不同的。 交叉连接只是两个表的笛卡尔积,与任何过滤标准或任何条件无关。

FULL OUTER JOIN给出两个表的LEFT OUTER JOIN和RIGHT OUTER JOIN的唯一结果集。它还需要ON子句来映射两列表。

Table 1 contains 10 rows and Table 2 contains 20 rows with 5 rows matching on specific columns. Then CROSS JOIN will return 10*20=200 rows in result set. FULL OUTER JOIN will return 25 rows in result set. INNER JOIN will return matching rows, hence, 5 rows in result set. FULL OUTER JOIN (or any other JOIN) always returns result set with less than or equal to Cartesian Product number. Number of rows returned by FULL OUTER JOIN equal to (No. of Rows by LEFT OUTER JOIN) + (No. of Rows by RIGHT OUTER JOIN) - (No. of Rows by INNER JOIN).

对于某些人来说,可能不太明显的一件事是,与空表(或结果集)的交叉连接将导致空表(M x N;因此M x 0 = 0)

一个完整的外部连接总是有行,除非M和N都是0。

交叉加入:http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm

TLDR;生成2个表之间所有可能的组合(Carthesian积)

(完整)外部加入:http://www.w3schools.com/Sql/sql_join_full.asp

TLDR;返回两个表中的每一行,以及具有相同值的结果(CONDITION中匹配)

除了返回NULL值之外,它们是相同的概念。

见下文:

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
*/