“INNER JOIN”和“OUTER JOIN”有什么区别?

另外如何做LEFT JOINRIGHT JOINFULL JOIN适合?

假设你正在join没有重复的列,这是一个非常常见的情况:

  • A和B的内部连接给出A相交B的结果,即维恩图交点的内部部分。

  • A和B的外部联结给出了联合B的结果,即维恩图联合的外部部分。

例子

假设你有两个表,每个表都有一列,数据如下:

 AB - - 1 3 2 4 3 5 4 6 

请注意,(1,2)对于A是唯一的,(3,4)是常见的,(5,6)对于B是唯一的。

内部联接

使用等效查询中的任何一个的内部连接给出两个表的交集,即它们具有共同的两行。

 select * from a INNER JOIN b on aa = bb; select a.*, b.* from a,b where aa = bb; a | b --+-- 3 | 3 4 | 4 

左外连接

左外连接将给出A中的所有行,以及B中的任何常见行。

 select * from a LEFT OUTER JOIN b on aa = bb; select a.*, b.* from a,b where aa = bb(+); a | b --+----- 1 | null 2 | null 3 | 3 4 | 4 

正确的外部连接

右外连接将给出B中的所有行,加上A中的任何常见行。

 select * from a RIGHT OUTER JOIN b on aa = bb; select a.*, b.* from a,b where aa(+) = bb; a | b -----+---- 3 | 3 4 | 4 null | 5 null | 6 

全外连接

一个完整的外连接会给你A和B的联合,即A中的所有行和B中的所有行。如果A中没有相应的B中的数据,则B部分为null,反之亦然。

 select * from a FULL OUTER JOIN b on aa = bb; a | b -----+----- 1 | null 2 | null 3 | 3 4 | 4 null | 6 null | 5 

你也可以考虑不同的连接types的以下模式;

加入的视觉解释

来源: CL-Moffatt详细解释的SQL-Joints的视觉表示

我推荐Jeff的博客文章 。 我见过的最好的描述,还有一个可视化,例如:

内部联接:

在这里输入图像描述

全外联:

在这里输入图像描述

维恩图并不真的为我做。

例如,它们在交叉连接和内部连接之间没有显示出任何区别,或者更一般地显示了不同types的连接谓词之间的区别,或者提供了关于如何操作的推理框架。

理解逻辑处理是无可替代的,而且无论如何也是相对直截了当的。

  1. 想象一下交叉连接。
  2. on第1步中的所有行评估on子句,并将谓词求值的地方保留为true
  3. (仅限外部连接)在步骤2中丢失的任何外部行中加回。

来源表

在这里输入链接描述

首先从CROSS JOIN (也称为笛卡尔积)开始。 这没有ON子句,只是返回两个表中的每一行的排列。

SELECT A.Colour,B.Colour FROM CROSS JOIN B

在这里输入链接描述

内部和外部连接有一个“ON”子句谓词。

  • 内部联接。 评估交叉连接结果中所有行的“ON”子句中的条件。 如果为true,则返回连接的行。 否则丢弃它。
  • 左外连接。 与内连接相同,那么左表中任何不匹配任何行的行都会为右表列输出空值。
  • 右外连接。 与内连接相同,那么右表中任何不匹配任何行的行都会为左表列输出这些值为NULL的值。
  • 全外联接。 与内连接相同,然后按照右外连接保留左外连接和右非匹配行中的左非匹配行。

一些例子

SELECT A.Colour,B.Colour FROM A INNER JOIN B ON A.Colour = B.Colour

以上是经典的equi连接。

内部联接

SELECT A.Colour,B.Colour FROM A INNER JOIN B ON A.Colour NOT IN('Green','Blue')

内部连接条件不一定是一个相等的条件,它不需要引用来自两个表(甚至任何一个)的列。 在交叉连接的每一行返回评估A.Colour NOT IN ('Green','Blue')

内心2

SELECT A.Colour,B.Colour FROM A INNER JOIN B ON 1 = 1

对于交叉连接结果中的所有行,连接条件的计算结果为true,因此这与交叉连接相同。 我不会再重复16行的图片。

SELECT A.Colour,B.Colour FROM LEFT OUTER JOIN B ON A.Colour = B.Colour

外连接的逻辑评估方式与内连接相同,不同的是,如果左表(左连接)中的某行不与右表中的任何行进行连接,则保留在结果中,其值为右边的列。

LOJ

SELECT A.Colour,B.Colour FROM LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour IS NULL

这只是简单地限制了以前的结果,只返回B.Colour IS NULL的行。 在这种情况下,这些行将被保留,因为它们在右表中没有匹配,并且查询返回表B不匹配的单个红色行。 这被称为反半连接。

IS NULLtestingselect一个非空的列是非常重要的,这个列不是空的,或者连接条件确保排除任何NULL值,以便这个模式正常工作,并避免只返回发生了碰撞的行除了未匹配的行之外,该列的NULL值。

loj是空的

SELECT A.Colour,B.Colour FROM RIGHT OUTER JOIN B ON A.Colour = B.Colour

右外连接的作用类似于左外连接,除了它们保留右表中的不匹配的行,并且null扩展左边的列。

ROJ

SELECT A.Colour,B.Colour FROM FULL OUTER JOIN B ON A.Colour = B.Colour

完全外连接将左右连接的行为组合在一起,并保留左右两个表中的不匹配行。

FOJ

SELECT A.Colour,B.Colour FROM A FULL OUTER JOIN B ON 1 = 0

交叉连接中没有行匹配1=0谓词。 两边的所有行都使用正常的外部连接规则保留,而另一边的表中的列则使用NULL。

FOJ 2

SELECT COALESCE(A.Colour,B.Colour)AS颜色从一个完整的外部连接B ON 1 = 0

通过对前面的查询进行小修改,可以模拟两个表中的UNION ALL

联盟所有

SELECT A.Colour,B.Colour FROM LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour ='Green'

请注意, WHERE子句(如果存在)在逻辑上运行在连接之后。 一个常见的错误是执行一个左外连接,然后在右表中包含一个条件为WHERE的子句,最后排除不匹配的行。 以上结束了执行外部连接…

LOJ

…然后“Where”子句运行。 NULL= 'Green'不计算为true,因此外部联接保留的行最终被丢弃(与蓝色一起),从而有效地将联接转换回内部联接。

LOJtoInner

如果意图是只包括来自B的行,其中颜色是绿色的,并且来自A的所有行不pipe正确的语法如何

SELECT A.Colour,B.Colour FROM LEFT OUTER JOIN B ON A.Colour = B.Colour AND B.Colour ='Green'

在这里输入图像描述

SQL小提琴

请参阅SQLFiddle.com上运行的这些示例。

以下摘自Graham Ellis在他的博客“马的嘴巴”中的文章“ MySQL – 左连接和右连接,内连接和外连接 ”。

在一个像MySQL这样的数据库中,数据被分成许多表,然后通过SELECT命令的JOIN将它们连接(连接)在一起,从多个表中读取logging。 阅读这个例子来看看它是如何工作的。

首先,一些样本数据:

 people mysql> select * from people; +------------+--------------+------+ | name | phone | pid | +------------+--------------+------+ | Mr Brown | 01225 708225 | 1 | | Miss Smith | 01225 899360 | 2 | | Mr Pullen | 01380 724040 | 3 | +------------+--------------+------+ 3 rows in set (0.00 sec) property mysql> select * from property; +------+------+----------------------+ | pid | spid | selling | +------+------+----------------------+ | 1 | 1 | Old House Farm | | 3 | 2 | The Willows | | 3 | 3 | Tall Trees | | 3 | 4 | The Melksham Florist | | 4 | 5 | Dun Roamin | +------+------+----------------------+ 5 rows in set (0.00 sec) 

常规join

如果我们做一个常规的JOIN(没有关键字INNER,OUTER,LEFT或RIGHT),那么我们得到在两个表中以适当的方式匹配的所有logging,并且两个传入表中不匹配的logging不被报告:

 mysql> select name, phone, selling from people join property on people.pid = property.pid; +-----------+--------------+----------------------+ | name | phone | selling | +-----------+--------------+----------------------+ | Mr Brown | 01225 708225 | Old House Farm | | Mr Pullen | 01380 724040 | The Willows | | Mr Pullen | 01380 724040 | Tall Trees | | Mr Pullen | 01380 724040 | The Melksham Florist | +-----------+--------------+----------------------+ 4 rows in set (0.01 sec) 

左join

如果我们做一个LEFT JOIN,我们得到所有匹配的logging,IN ADDITION我们为每个连接的左边表中的每个不匹配的logging获得一个额外的logging – 从而确保(在这个例子中)每个PERSON都被提到:

  mysql> select name, phone, selling from people left join property on people.pid = property.pid; +------------+--------------+----------------------+ | name | phone | selling | +------------+--------------+----------------------+ | Mr Brown | 01225 708225 | Old House Farm | | Miss Smith | 01225 899360 | NULL <<-- unmatch | | Mr Pullen | 01380 724040 | The Willows | | Mr Pullen | 01380 724040 | Tall Trees | | Mr Pullen | 01380 724040 | The Melksham Florist | +------------+--------------+----------------------+ 5 rows in set (0.00 sec) 

正确的join

如果我们做了一个右连接,我们得到所有匹配的logging,并在连接的右表中为每个不匹配的logging添加额外的logging – 在我的例子中,这意味着即使我们不有卖家详细资料:

 mysql> select name, phone, selling from people right join property on people.pid = property.pid; +-----------+--------------+----------------------+ | name | phone | selling | +-----------+--------------+----------------------+ | Mr Brown | 01225 708225 | Old House Farm | | Mr Pullen | 01380 724040 | The Willows | | Mr Pullen | 01380 724040 | Tall Trees | | Mr Pullen | 01380 724040 | The Melksham Florist | | NULL | NULL | Dun Roamin | +-----------+--------------+----------------------+ 5 rows in set (0.00 sec) 

INNER JOIN与第一个例子完全一样,并且OUTER可以在后两个例子中的LEFT或RIGHT之后加上 – 它提供了ODBC兼容性,并且不增加额外的function。

内部联接

仅检索匹配的行,即A intersect B

在这里输入图像说明

 SELECT * FROM dbo.Students S INNER JOIN dbo.Advisors A ON S.Advisor_ID = A.Advisor_ID 

左外连接

从第一个表中select所有logging,并select第二个表中与连接键匹配的logging。

在这里输入图像说明

 SELECT * FROM dbo.Students S LEFT JOIN dbo.Advisors A ON S.Advisor_ID = A.Advisor_ID 

全外联接

select第二个表中的所有logging,以及第一个表中与连接的键匹配的logging。

在这里输入图像说明

 SELECT * FROM dbo.Students S FULL JOIN dbo.Advisors A ON S.Advisor_ID = A.Advisor_ID 

参考

  • 内部和外部连接SQL示例和Join块

  • SQL:JOINS

简而言之:

内部联接仅检索匹配的行。

外部联接从一个表中检索匹配的行,而在其他表中检索匹配的行….结果取决于您使用的是哪一个:

  • :右表中的匹配行和左表中的所有行

  • :左表中的匹配行和右表或中的所有行

  • 完整 :所有表中的所有行。 是否匹配没关系

如果在连接的另一个(右侧)存在匹配的logging,则内部连接仅显示行。

即使在连接的另一侧(右侧)没有匹配的行,(左)外部连接也会在左侧显示每条logging的行。 如果没有匹配的行,其他(右侧)列将显示空值。

连接用于合并来自两个表的数据,结果是一个新的临时表。 联接是基于谓词谓词来执行的,该谓词指定了用于执行联接的条件。 内连接和外连接的不同之处在于内连接将仅返回基于连接谓词实际匹配的行。 让我们考虑员工和地点表:

在这里输入图像描述

内部连接: –内部连接通过基于连接谓词组合两个表( EmployeeLocation )的列值来创build新的结果表。 查询将Employee的每一行与Location的每一行进行比较,以查找满足join-predicate的所有行对。 当通过匹配非NULL值满足连接谓词时, EmployeeLocation的每对匹配行的列值将组合到结果行中。 以下是内连接的SQL如下所示:

 select * from employee inner join location on employee.empID = location.empID OR select * from employee, location where employee.empID = location.empID 

现在,下面是运行这个SQL的结果: 在这里输入图像描述 在这里输入图像描述

外连接: –外连接不要求两个连接表中的每个logging都有匹配的logging。 即使没有其他匹配的logging,连接的表格也会保留每条logging。 外连接进一步细分为左外连接和右外连接,具体取决于保留哪些表的行(左侧或右侧)。

左外部联接: –对于表EmployeeLocation的 左外部联接 (或简单地,左联接)的结果始终包含“左”表( Employee )的所有logging,即使联接条件没有find任何匹配的logging“右”表( 位置 )。 以下是使用上面的表对左外连接的SQL的样子:

 select * from employee left outer join location on employee.empID = location.empID; //Use of outer keyword is optional 

现在,运行这个SQL的结果如下所示: 在这里输入图像描述 在这里输入图像描述

右外连接:右外连接(或右连接)与左外连接非常相似,除了表格的处理方式相反。 “右”表( 位置 )的每一行至less会出现在连接表中一次。 如果不存在来自“左”表( Employee )的匹配行,那么对于那些在位置中不匹配的logging,NULL将出现在Employee的列中。 这是SQL的样子:

 select * from employee right outer join location on employee.empID = location.empID; //Use of outer keyword is optional 

使用上面的表格,我们可以显示右外连接的结果集是什么样的:

在这里输入图像描述 在这里输入图像描述

完全外连接: –全外连接或全连接是通过在连接的结果中包含不匹配的行来保留不匹配的信息,使用完整的外连接。 它包括来自两个表的所有行,而不pipe另一个表是否具有匹配的值。 在这里输入图像描述

图片来源

内部连接要求在连接表中存在具有相关ID的logging。

外部连接将返回左侧的logging,即使右侧没有任何内容。

例如,你有一个Orders和一个OrderDetails表。 他们通过“OrderID”相关联。

命令

  • 订单ID
  • 顾客姓名

订单详细信息

  • OrderDetailID
  • 订单ID
  • 产品名称
  • 数量
  • 价钱

请求

 SELECT Orders.OrderID, Orders.CustomerName FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID 

只会返回在OrderDetails表中也有一些东西的订单。

如果您将其更改为外部左连接

 SELECT Orders.OrderID, Orders.CustomerName FROM Orders LEFT JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID 

那么即使它们没有OrderDetailslogging,它也会从Orders表中返回logging。

你可以使用这个来find没有任何OrderDetails的订单,通过添加一个WHERE OrderDetails.OrderID IS NULL子句如WHERE OrderDetails.OrderID IS NULL指示可能的孤行订单。

简而言之:

内部连接 – >仅从父表和子表中取出常用loggingWHITER表的主键与子表中的外键匹配。

左连接 – >

伪代码

 1.Take All records from left Table 2.for(each record in right table,) { if(Records from left & right table matching on primary & foreign key){ use their values as it is as result of join at the right side for 2nd table. } else { put value NULL values in that particular record as result of join at the right side for 2nd table. } } 

正确的join :正好与左边的join相反。 将表名称放在Right join的右侧的LEFT JOIN中,得到与LEFT JOIN相同的输出。

外部连接 :显示两个表中的所有loggingNo matter what 。 如果Left表中的logging与基于Primary,Forieign键的右表不匹配,则使用NULL值作为join的结果。

例如:

例

现在假设为2个表

1.employees , 2.phone_numbers_employees

 employees : id , name phone_numbers_employees : id , phone_num , emp_id 

在这里,雇员表是主表,phone_numbers_employees是子表(它包含emp_id作为外键,连接employee.id所以它的子表)。

内部连接

只有雇员表(其ID)的主键匹配子表phone_numbers_employees(emp_id)的外键,才能取得2个表的logging。

所以查询将是:

 SELECT e.id , e.name , p.phone_num FROM employees AS e INNER JOIN phone_numbers_employees AS p ON e.id = p.emp_id; 

这里只取主键=外键上的匹配行,如上所述。主键上的不匹配行=外键因连接而被跳过。

左连接

左连接保留左表的所有行,而不pipe在右表上是否有匹配的行。

 SELECT e.id , e.name , p.phone_num FROM employees AS e LEFT JOIN phone_numbers_employees AS p ON e.id = p.emp_id; 

外连接

 SELECT e.id , e.name , p.phone_num FROM employees AS e OUTER JOIN phone_numbers_employees AS p ON e.id = p.emp_id; 

graphics看起来像:

图

您使用INNER JOIN从两个表中返回匹配的所有行。 即在结果表中,所有的行和列将有值。

OUTER JOIN结果表可能有空列。 外连接可以是LEFTRIGHT

即使第二个表中没有匹配, LEFT OUTER JOIN将返回第一个表中的所有行。

即使第一个表中没有匹配, RIGHT OUTER JOIN将返回第二个表中的所有行。

这是对联接的一个很好的解释

对于所有types的连接,这是一个很好的图解说明

来源: http : //ssiddique.info/understanding-sql-joins-in-easy-way.html

INNER JOIN要求比较两个表中至less有一个匹配。 例如,表A和表B意味着A 8 B(交点B)。

LEFT OUTER JOIN and LEFT JOIN are the same. It gives all the records matching in both tables and all possibilities of the left table.

Similarly, RIGHT OUTER JOIN and RIGHT JOIN are the same. It gives all the records matching in both tables and all possibilities of the right table.

FULL JOIN is the combination of LEFT OUTER JOIN and RIGHT OUTER JOIN without duplication.

The answer is in the meaning of each one, so in the results.

Note :
In SQLite there is no RIGHT OUTER JOIN or FULL OUTER JOIN .
And also in MySQL there is no FULL OUTER JOIN .

My answer is based on above Note .

When you have two tables like these:

 --[table1] --[table2] id | name id | name ---+------- ---+------- 1 | a1 1 | a2 2 | b1 3 | b2 

CROSS JOIN / OUTER JOIN :
You can have all of those tables data with CROSS JOIN or just with , like this:

 SELECT * FROM table1, table2 --[OR] SELECT * FROM table1 CROSS JOIN table2 --[Results:] id | name | id | name ---+------+----+------ 1 | a1 | 1 | a2 1 | a1 | 3 | b2 2 | b1 | 1 | a2 2 | b1 | 3 | b2 

INNER JOIN :
When you want to add a filter to above results based on a relation like table1.id = table2.id you can use INNER JOIN :

 SELECT * FROM table1, table2 WHERE table1.id = table2.id --[OR] SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id --[Results:] id | name | id | name ---+------+----+------ 1 | a1 | 1 | a2 

LEFT [OUTER] JOIN :
When you want to have all rows of one of tables in the above result -with same relation- you can use LEFT JOIN :
(For RIGHT JOIN just change place of tables)

 SELECT * FROM table1, table2 WHERE table1.id = table2.id UNION ALL SELECT *, Null, Null FROM table1 WHERE Not table1.id In (SELECT id FROM table2) --[OR] SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id --[Results:] id | name | id | name ---+------+------+------ 1 | a1 | 1 | a2 2 | b1 | Null | Null 

FULL OUTER JOIN :
When you also want to have all rows of the other table in your results you can use FULL OUTER JOIN :

 SELECT * FROM table1, table2 WHERE table1.id = table2.id UNION ALL SELECT *, Null, Null FROM table1 WHERE Not table1.id In (SELECT id FROM table2) UNION ALL SELECT Null, Null, * FROM table2 WHERE Not table2.id In (SELECT id FROM table1) --[OR] (recommended for SQLite) SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id UNION ALL SELECT * FROM table2 LEFT JOIN table1 ON table2.id = table1.id WHERE table1.id IS NULL --[OR] SELECT * FROM table1 FULL OUTER JOIN table2 On table1.id = table2.id --[Results:] id | name | id | name -----+------+------+------ 1 | a1 | 1 | a2 2 | b1 | Null | Null Null | Null | 3 | b2 

Well, as your need you choose each one that covers your need ;).

In SQL, A join is used to compare and combine — literally join — and return specific rows of data from two or more tables in a database. An inner join finds and returns matching data from tables, while an outer join finds and returns matching data and some dissimilar data from tables.

Inner Join

An inner join focuses on the commonality between two tables. When using an inner join , there must be at least some matching data between two (or more) tables that are being compared. An inner join searches tables for matching or overlapping data. Upon finding it, the inner join combines and returns the information into one new table.

Example of Inner Join

Let's consider a common scenario of two tables: product prices and quantities. The common information in the two tables is product name, so that is the logical column to join the tables on. There are some products that are common in the two tables; others are unique to one of the tables and don't have a match in the other table.

An inner join on Products returns information about only those products that are common in both tables.

Inner join

Outer Join

An outer join returns a set of records (or rows) that include what an inner join would return but also includes other rows for which no corresponding match is found in the other table.

There are three types of outer joins:

  • Left Outer Join (or Left Join)
  • Right Outer Join (or Right Join)
  • Full Outer Join (or Full Join) Each of these outer joins refers to the part of the data that is being compared, combined, and returned. Sometimes nulls will be produced in this process as some data is shared while other data is not.

Left Outer Join

A left outer join will return all the data in Table 1 and all the shared data (so, the inner part of the Venn diagram example), but only corresponding data from Table 2, which is the right join.

Left Join Example

In my example database, there are two products — oranges and tomatoes — on the 'left' (Prices table) that do not have a corresponding entry on the 'right' (Quantities table). In a left join , these rows are included in the result set with a NULL in the Quantity column. The other rows in the result are the same as the inner join.

Outer_left

Right Outer Join

A right outer join returns Table 2's data and all the shared data, but only corresponding data from Table 1, which is the left join.

Right Join Example

Similar to the left join example, the output of a right outer join includes all rows of the inner join and two rows — broccoli and squash — from the 'right' (Quantities table) that do not have matching entries on the left.

right-join

Full Outer Join

A full outer join , or full join , which is not supported by the popular MySQL database management system, combines and returns all data from two or more tables, regardless of whether there is shared information. Think of a full join as simply duplicating all the specified information, but in one table, rather than multiple tables. Where matching data is missing, nulls will be produced.

Full-Outer_join

The difference is in the way tables are joined if there are no common records.

  • JOIN is same as INNER JOIN and means to only show records common to both tables. Whether the records are common is determined by the fields in join clause. 例如:

     FROM t1 JOIN t2 on t1.ID = t2.ID 

    means show only records where the same ID value exists in both tables.

  • LEFT JOIN is same as LEFT OUTER JOIN and means to show all records from left table (ie the one that precedes in SQL statement) regardless of the existance of matching records in the right table.

  • RIGHT JOIN is same as RIGHT OUTER JOIN and means opposite of LEFT JOIN , ie shows all records from the second (right) table and only matching records from first (left) table.

Source: What's the difference between LEFT, RIGHT, INNER, OUTER, JOIN?

Inner join.

A join is combining the rows from two tables. An inner join attempts to match up the two tables based on the criteria you specify in the query, and only returns the rows that match. If a row from the first table in the join matches two rows in the second table, then two rows will be returned in the results. If there's a row in the first table that doesn't match a row in the second, it's not returned; likewise, if there's a row in the second table that doesn't match a row in the first, it's not returned.

Outer Join.

A left join attempts to find match up the rows from the first table to rows in the second table. If it can't find a match, it will return the columns from the first table and leave the columns from the second table blank (null).

I don't see much details about performance and optimizer in the other answers.

Sometimes it is good to know that only INNER JOIN is associative which means the optimizer has the most option to play with it. It can reorder the join order to make it faster keeping the same result. The optimizer can use the most join modes.

Generally it is a good practice to try to use INNER JOIN instead of the different kind of joins. (Of course if it is possible considering the expected result set.)

There are a couple of good examples and explanation here about this strange associative behavior:

  • Are left outer joins associative?
  • Does the join order matter in SQL?

The difference is in the way tables are joined if there are no common records.

JOIN is same as INNER JOIN and means to only show records common to both tables. Whether the records are common is determined by the fields in join clause.

例如:

 SELECT * FROM t1 JOIN t2 on t1.ID = t2.ID 

It means show only records where the same ID value exists in both tables.

LEFT JOIN is same as LEFT OUTER JOIN and means to show all records from left table (ie the one that precedes in SQL statement) regardless of the existence of matching records in the right table.

RIGHT JOIN is same as RIGHT OUTER JOIN and means opposite of LEFT JOIN , ie shows all records from the second (right) table and only matching records from first (left) table.

Having criticized the much-loved red-shaded Venn diagram, I thought it only fair to post my own attempt.

Although @Martin Smith's answer is the best of this bunch by a long way, his only shows the key column from each table, whereas I think ideally non-key columns should also be shown.

The best I could do in the half hour allowed, I still don't think it adequately shows that the nulls are there due to absence of key values in TableB or that OUTER JOIN is actually a union rather than a join:

在这里输入图像描述

The precise algorithm for INNER JOIN , LEFT/RIGHT OUTER JOIN are like as following:

  1. Take each row from the first table: a
  2. Consider all rows from second table beside it: (a, b[i])
  3. Evaluate the ON clause against each pair: ON(a, b[i]) = true/false?
    • When the condition evaluates to true , return it.
    • For (left/right) Outer Joins : if reach end of second table without any match, return a ( virtual ) pair using Null for all columns of second table: (a, Null) . This is to ensure all rows of first table exists in final results.

Note: the condition specified in ON clause could be anything, it is not required to use Primary Keys and you don't need to always refer to Columns from both tables! 例如:

  • ... ON T1.title = T2.title AND T1.version < T2.version ( => see this post as a sample usage: Select only rows with max value on a column )
  • ... ON T1.y IS NULL
  • ... ON 1 = 0 (just as sample)

Inner Join vs. Left Outer Join


在这里输入图像描述

You can see also this answer in current page for more samples.

Inner Join An inner join focuses on the commonality between two tables. When using an inner join, there must be at least some matching data between two (or more) tables that are being compared. An inner join searches tables for matching or overlapping data. Upon finding it, the inner join combines and returns the information into one new table.

Outer Join An outer join returns a set of records (or rows) that include what an inner join would return but also includes other rows for which no corresponding match is found in the other table.

There are three types of outer joins:

Left Outer Join (or Left Join) Right Outer Join (or Right Join) Full Outer Join (or Full Join) Each of these outer joins refers to the part of the data that is being compared, combined, and returned. Sometimes nulls will be produced in this process as some data is shared while other data is not.

Simplest Definitions

Inner Join: Returns matched records from both tables.

Full Outer Join: Returns matched and unmatched records from both tables with null for unmatched records from Both Tables .

Left Outer Join: Returns matched and unmatched records only from table on Left Side .

Right Outer Join: Returns matched and unmatched records only from table on Right Side .

In-Short

Matched + Left Unmatched + Right Unmatched = Full Outer Join

Matched + Left Unmatched = Left Outer Join

Matched + Right Unmatched = Right Outer Join

Matched = Inner Join

INNER JOIN

An inner join produces a result set that is limited to the rows where there is a match in both tables for what we're looking for. If you don't know which kind of join you need, this will usually be your best bet.

LEFT OUTER JOIN

A left outer join, or left join, results in a set where all of the rows from the first, or left hand side, table are preserved. The rows from the second, or right hand side table only show up if they have a match with the rows from the first table. Where there are values from the left table but not from the right, the table will read null, which means that the value has not been set.

RIGHT OUTER JOIN

A right outer join, or right join, is the same as a left join, except the roles are reversed. All of the rows from the right hand side table show up in the result, but the rows from the table on the left are only there if they match the table on the right. Empty spaces are null, just like with the the left join.

FULL OUTER JOIN

A full outer join, or just outer join, produces a result set with all of the rows of both tables, regardless of whether there are any matches. Similarly to the left and right joins, we call the empty spaces null.

For More Reference

What is the difference between “INNER JOIN” and “OUTER JOIN”?

They are the most commonly used existential operators in SQL, where INNER JOIN is used for 'exists' and LEFT OUTER JOIN is used for 'does not exist'.

Consider these queries:

 users who have posted and have votes users who have posted but have no badges 

People who look for set-based solutions (an industry term) would recognise the respective queries as:

 users who have posted INTERSECT users who have votes users who have posted MINUS users who have badges 

Translating these into standard SQL:

 SELECT UserId FROM Posts INTERSECT SELECT UserId FROM Votes; SELECT UserId FROM Posts EXCEPT SELECT UserId FROM Badges; 

Others will think along similar lines of set inclusion:

 users who have posted and IN the set of users who have votes users who have posted and NOT IN the set of users who have badges 

Translating these into standard SQL:

 SELECT UserId FROM Posts WHERE UserId IN ( SELECT UserId FROM Votes ); SELECT UserId FROM Posts WHERE UserId NOT IN ( SELECT UserId FROM Badges ); 

Some will think in terms of 'existance' within sets eg

 users who have posted and EXIST in the set of users who have votes users who have posted and do NOT EXIST in the set of users who have badges 

Translating these into standard SQL (note we now need to use range variables ie p , v , b ):

 SELECT p.UserId FROM Posts p WHERE EXISTS ( SELECT * FROM Votes v WHERE v.UserId = p.UserId ); SELECT p.UserId FROM Posts p WHERE NOT EXISTS ( SELECT * FROM Badges b WHERE b.UserId = p.UserId ); 

However, I've found that the "industry standard" approach is to exclusively use joins. I don't know what the thinking is here ( Law of the Instrument ? Premature optimization ?), so I'll go staight to the syntax:

 SELECT p.UserId FROM Posts p INNER JOIN Votes v ON v.UserId = p.UserId; SELECT p.UserId FROM Posts p LEFT JOIN Badges b ON b.UserId = p.UserId WHERE b.UserId IS NULL; 

注意事项:

  • The only projection is from Users but we still need all those range variables ( p , v , b ) for search conditions.
  • The UserId IS NULL search condition 'belongs' to the the OUTER JOIN but is disconnected in the query.
  • LEFT is the industry standard: professionals will rewrite a query to avoid using RIGHT !
  • The OUTER keyword from LEFT OUTER JOIN is omitted.

Closing remarks:

Sometimes joins are used in queries solely to determine whether values exist or do not exists in another set. Learn to look carefully at the attributes being projected (the columns in the SELECT clause): if there are none from the joined table then they are simply being used as existential operators. Additionally for outer join, look for instances of <key_column> IS NULL .

  • Inner join – An inner join using either of the equivalent queries gives the intersection of the two tables , ie the two rows they have in common.

  • Left outer join – A left outer join will give all rows in A, plus any common rows in B.

  • Full outer join – A full outer join will give you the union of A and B, ie All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versay

1. Inner Join: Also called as Join. It returns the rows present in both the Left table, and right table only if there is a match . Otherwise, it returns zero records.

例:

 SELECT e1.emp_name, e2.emp_salary FROM emp1 e1 INNER JOIN emp2 e2 ON e1.emp_id = e2.emp_id 

output1

2. Full Outer Join: Also called as Full Join. It returns all the rows present in both the Left table, and right table.

例:

 SELECT e1.emp_name, e2.emp_salary FROM emp1 e1 FULL OUTER JOIN emp2 e2 ON e1.emp_id = e2.emp_id 

output2

3. Left Outer join: Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).

4. Right Outer Join: Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.

joins

Advantages of Joins

  1. Executes faster.

Both inner and outer joins are used to combine rows from two or more tables into a single result. This is done using a join condition. The join condition specifies how columns from each table are matched to one another. In most cases the aim is to find equal values between tables, and include those matches.

The most common case for this is when you're matching the foreign key of one table to the primary key of another, such as when using and ID to lookup a value.

Though both inner and outer joins include rows from both tables when the match condition is successful, they differ in how they handle a false match condition.

Inner joins don't include non-matching rows; whereas, outer joins do include them. Let's dig a little deeper into the mechanics of each

Inner Join Mechanics

An inner join is used to return results by combining rows from two or more tables.

In its simplest case, where there is no join condition, an inner join would combine all rows from one table with those from another. If the first table contained three rows, and the second, four, then the final result would contain twelve (3 x 4 = 12) !

The purpose of the join condition is to limit which rows are combined. In most cases we limit rows to those matching a column. If a person has more than one phone number, then more than one match is made. From this you can see we may get more rows returned than we have for each person.

在这里输入图像描述

Tables to Join Conversely, if a person has no phone number, then there won't be an entry in PersonPhone, and no match made. That particular person won't be included in the results, as only those with matches are included. Let's try an example. Suppose the HR Manager wants to create a phone directory. They want the person's first name, last name, title, and phone numbers. What query could you use to create this? Here is one that would do the trick:

 SELECT P.FirstName, P.LastName, P.Title, PH.PhoneNumber FROM Person.Person AS P INNER JOIN Person.PersonPhone AS PH ON P.BusinessEntityID = PH.BusinessEntityID AND PH.PhoneNumberTypeID = 3 ORDER BY P.LastName 

The INNER JOIN specifies which tables to join and the match condition for doing so. The condition PH.Phone NumberTyeID = 3 limits the query to work numbers. If you run the above, you get the following results:

在这里输入图像描述

Inner Join Results Keep in mind the inner join only returns row where the match condition is true. In this example, rows where the BusinessEntityID's don't match aren't included. This could be an issue if a person doesn't have a phone number as those employees wouldn't be on the list. If you wish to include these employees you can use an Outer join.

Outer Join Mechanics

An outer join is used to return results by combining rows from two or more tables. But unlike an inner join, the outer join will return every row from one specified table, even if the join condition fails. Take the phone directory example above. If the HR manager wanted to list every employee regardless of whether they had a work phone number, then using an outer join would make it so.

 SELECT P.FirstName, P.LastName, P.Title, PH.PhoneNumber FROM Person.Person AS P LEFT OUTER JOIN Person.PersonPhone AS PH ON P.BusinessEntityID = PH.BusinessEntityID AND PH.PhoneNumberTypeID = 3 ORDER BY P.LastName 

You can learn more about left and right outer joins in this article, for now just understand that when a LEFT OUTER JOIN is used, all rows for the table in the FROM clause are included in the result, even if a match isn't found with the other table. When a match isn't found, then a NULL is place in the column. You can see this in action below:

在这里输入图像描述 Outer Join Results Notice in the example the PhoneNumber for Catherine Abel is NULL. This is because Catherine's work number isn't listed, and no match was found during the join. If this would have been an inner join, then this row wouldn't have been included in the results.

In Simple Terms,

1. INNER JOIN OR EQUI JOIN : Returns the resultset that matches only the condition in both the tables.

2. OUTER JOIN : Returns the resultset of all the values from both the tables even if there is condition match or not.

3. LEFT JOIN : Returns the resultset of all the values from left table and only rows that match the condition in right table.

4. RIGHT JOIN : Returns the resultset of all the values from right table and only rows that match the condition in left table.

5. FULL JOIN : Full Join and Full outer Join are same.