什么是默认的T-SQL JOIN行为,INNER或OUTER?

时间:2014-05-06 16:50:27

标签: sql sql-server tsql

此问题已被要求MySQL,但对于Transact-SQL,默认的JOIN行为是什么?

也就是说,只是在一个与写JOIN同义的查询中写INNER JOIN(就像MySQL的情况一样),或其他东西,比如FULL OUTER JOIN

3 个答案:

答案 0 :(得分:18)

JOIN默认为INNER JOIN行为。

为验证这一点,我运行了以下代码:

DECLARE @A TABLE (x INT)
INSERT INTO @A
    SELECT 1 UNION ALL
    SELECT 2

DECLARE @B TABLE (x INT)
INSERT INTO @B
    SELECT 2 UNION ALL
    SELECT 3

SELECT 
    A.x AS 'A.x', 
    B.x AS 'B.x'
FROM @A A
JOIN @B B
    ON A.x = B.x

这只产生一行,符合INNER JOIN行为:

A.x  | B.x
-----+-----
2    | 2

将其与FULL OUTER JOIN

进行对比
...

SELECT 
    A.x AS 'A.x', 
    B.x AS 'B.x'
FROM @A A
FULL OUTER JOIN @B B
    ON A.x = B.x

这当然显示了所有三行:

A.x  | B.x
-----+-----
1    | NULL
2    | 2
NULL | 3

答案 1 :(得分:9)

在T-SQL中,没有显式类型的JOININNER JOIN,由the documentation on the FROM clause指定(摘录):

[ FROM { <table_source> } [ ,...n ] ]   
<table_source> ::=   
{  
    ...
    | <joined_table>
    ...   
}  

<joined_table> ::=   
{  
    <table_source> <join_type> <table_source> ON <search_condition>
    ...   
}  

<join_type> ::=   
    [ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]  
    JOIN  
  

<强> INNER

     

指定返回所有匹配的行对。丢弃   两个表中不匹配的行。如果未指定连接类型,则为此   是默认值。

答案 2 :(得分:3)

For some MSDN reference. To paraphrase, inner join is the default type of join.

https://msdn.microsoft.com/en-us/library/zt8wzxy4.aspx