跳转到内容

连接:修订间差异

维基百科,自由的百科全书
删除的内容 添加的内容
Iridiumcao留言 | 贡献
自然连接:​ 加了个标点
Iridiumcao留言 | 贡献
第145行: 第145行:
==== 交叉连接 ====
==== 交叉连接 ====


'''交叉连接'''('''cross join'''), 又称'''[[笛卡尔连接]]'''('''cartesian join''')或'''[[叉乘]]'''('''Product'''), 它是所有类型的内连接的基础. 把表视为行记录的集合, 交叉连接即返回这两个集合的[[笛卡尔积]]. 这其实等价于内连接的链接条件为"永真", 或连接条件不存在.
A '''cross join''', '''[[cartesian join]]''' or '''[[Product (mathematics)|product]]''' provides the foundation upon which all types of inner joins operate. A cross join returns the [[cartesian product]] of the sets of records from the two joined tables. Thus, it equates to an inner join where the join-condition always evaluates to ''True'' or where the join-condition is absent from the statement.


If A and B are two sets, then the cross join is written as A × B.
如果 A B 是两个集合, 它们的交叉连接就记为: A × B.


The SQL code for a cross join lists the tables for joining (<code>[[From (SQL)|FROM]]</code>), but does not include any filtering join-predicate.
用于交叉连接的 SQL 代码在 <code>[[From (SQL)|FROM]]</code> 列出表名, 但并不包含任何过滤的连接谓词.


显式的交叉连接实例:
Example of an explicit cross join:
<source lang=sql>
<source lang=sql>
SELECT *
SELECT *
第157行: 第157行:
</source>
</source>


隐式的交叉连接实例:
Example of an implicit cross join:
<source lang=sql>
<source lang=sql>
SELECT *
SELECT *
第216行: 第216行:
|}
|}


交叉连接不会应用任何谓词去过滤结果表中的记录. 程序员可以用 <code>WHERE</code> 语句进一步过滤结果集.
The cross join does not apply any predicate to filter records from the joined table. Programmers can further filter the results of a cross join by using a <code>WHERE</code> clause.


== 外连接 ==
== 外连接 ==

2009年9月17日 (四) 14:47的版本

SQL 的连接(JOIN)语句将数据库中的两个或多个表组合起来.[1] 由"连接"生成的集合, 可以被保存为表, 或者当成表来使用. JOIN 语句的含义是把两张表的属性通过它们的值组合在一起. 基于 ANSI 标准的 SQL 列出了四种 JOIN 方式: 内连接(INNER), 外连接(OUTER), 左外连接(LEFT), 和右外连接(RIGHT). 在特定的情况下, 一张表(基本表, 视图, 或连接表)可以和自身进行连接, 成为自连接(self-join).

程序员用 JOIN 谓词表示要得到"连接"后的集合. 如果evaluated predicate为真, 组合后的记录就会按照预期的方式生成, 如一个记录集, 或者一张临时表.

示例用表

下文中解释"连接"都将用到这里的两张表. 表中的记录(行)用于演示不同类型的"连接"和"连接谓词"的作用. 在下面两张表中, Department.DepartmentID 是主键, Employee.DepartmentID 是外键.

雇员表(Employee)
LastName DepartmentID
Rafferty 31
Jones 33
Steinberg 33
Robinson 34
Smith 34
Jasper
部门表(Department)
DepartmentID DepartmentName
31 Sales
33 Engineering
34 Clerical
35 Marketing


注: "Marketing" 部门目前没有员工列出. 同样, 雇员 "Jasper" 不在 Department 表中的任何一个部门.

内连接

内连接(inner join)是应用程序中用的普遍的"连接"操作, 它一般都是默认的连接类型. 内连接基于连接谓词将两张表(如 A 和 B)的列组合在一起, 产生新的结果表. 查询会将 A 表的每一行和 B 表的每一行进行比较, 并找出满足连接谓词的组合. 当连接谓词被满足, A 和 B 中匹配的行会按列组合(并排组合)成结果集中的一行. 连接产生的结果集, 可以定义为首先对两张表做笛卡尔积(交叉连接) -- 将 A 中的每一行和 B 中的每一行组合, 然后返回满足连接谓词的记录. 实际上 SQL 产品会尽可能用其他方式去实现连接, 笛卡尔积运算是非常没效率的.

SQL 定义了两种不同语法方式去表示"连接". 首先是"显示连接符号", 它显示地使用关键字 JOIN, 其次是"隐式连接符号", 它使用所谓的"隐式连接符号". 隐式连接符号把需要连接的表放到 SELECT 语句的 FROM 部分, 并用逗号隔开. 这样就构成了一个"交叉连接", WHERE 语句可能放置一些过滤谓词(过滤条件). 那些过滤谓词在功能上等价于显式连接符号.

内连接"可以进一步被分为: 相等连接, 自然连接, 和交叉连接(见下).

程序要应该特别注意连接依据的列可能包含 NULL 值, NULL 值不与任何值匹配(甚至和它本身) -- 除非连接条件中显式地使用 IS NULLIS NOT NULL 等谓词.

例如, 下面的查询通过 Employee 表和 Department 表共有的属性 DepartmentID 连接两表. 在两表 DepartmentID 匹配之处(如连接谓词被满足), 查询将组合两表的 LastName, DepartmentIDDepartmentName 等列, 把它们放到结果表的一行(一条记录)里. 当 DepartmentID 不匹配, 就不会往结果表中生成任何数据.

显式的内连接实例:

SELECT *
FROM   employee 
       INNER JOIN department 
          ON employee.DepartmentID = department.DepartmentID

等价于:

SELECT *  
FROM   employee, department 
WHERE  employee.DepartmentID = department.DepartmentID

显式的内连接的输出结果:

Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID
Robinson 34 Clerical 34
Jones 33 Engineering 33
Smith 34 Clerical 34
Steinberg 33 Engineering 33
Rafferty 31 Sales 31

雇员 "Jasper" 和部门 "Marketing" 都未出现. 它们在预期得到的表中没有任何匹配的记录: "Jasper" 没有关联的部门, 而号码为35的部门中没有任何雇员. 这样, 在"连接"后的表中, 就没有关于 Jasper 或 Marketing 的信息了. 相对于预期的结果, 这个行为可能是一个微妙的臭虫(bug). 外连接可能可以避免这种情况.

相等链接

相等连接 (equi-join, 或 equijoin), 是比较连接(θ连接)的一种特例, 它的连接谓词只用了相等比较. 使用其他比较操作符(如 <)的不是相等连接. 前面的查询已经展示了一个相等连接的实例:

SELECT *
FROM   employee 
       INNER JOIN department 
          ON employee.DepartmentID = department.DepartmentID

SQL 提供了一种可选的简短符号去表达相等连接, 它使用 USING 关键字 (Feature ID F402):

SELECT *
FROM   employee 
       INNER JOIN department 
          USING (DepartmentID)

USING 结构并不仅仅是语法糖, 上面查询的结果和使用显式谓词得到的查询得到的结果是不同的. 特别地, 在 USING 部分列出的列(column)将以只出现一次, 且名称无表名修饰.在上面的例子中, 将产生单独的名为 DepartmentID 的列, 而不是 employee.DepartmentIDdepartment.DepartmentID.

USING 语句先以被 MySQL, Oracle, PostgreSQL, SQLite, 和 DB2/400 等产品支持.

自然连接

自然连接比相等连接的进一步特例化. 两表做自然连接时, 两表中的所有名称相同的列都将被比较, 这是隐式的. 自然连接得到的结果表中, 两表中名称相同的列只出现一次.

上面用于内连接的查询实例可以用自然连接的方式表示如下:

SELECT *
FROM   employee NATURAL JOIN department

用了 USING 语句后, 在连接表中, DepartmentID 列只出现一次, 且没有表名作前缀:

DepartmentID Employee.LastName Department.DepartmentName
34 Smith Clerical
33 Jones Engineering
34 Robinson Clerical
33 Steinberg Engineering
31 Rafferty Sales

Oracle 里用 JOIN USINGNATURAL JOIN 时, 如果两表共有的列的名称前加上某表名作为前缀, 则会报编译错误: "ORA-25154: column part of USING clause cannot have qualifier" 或 "ORA-25155: column used in NATURAL join cannot have qualifier".

交叉连接

交叉连接(cross join), 又称笛卡尔连接(cartesian join)或叉乘(Product), 它是所有类型的内连接的基础. 把表视为行记录的集合, 交叉连接即返回这两个集合的笛卡尔积. 这其实等价于内连接的链接条件为"永真", 或连接条件不存在.

如果 A 和 B 是两个集合, 它们的交叉连接就记为: A × B.

用于交叉连接的 SQL 代码在 FROM 列出表名, 但并不包含任何过滤的连接谓词.

显式的交叉连接实例:

SELECT *
FROM   employee CROSS JOIN department

隐式的交叉连接实例:

SELECT *
FROM   employee, department;
Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID
Rafferty 31 Sales 31
Jones 33 Sales 31
Steinberg 33 Sales 31
Smith 34 Sales 31
Robinson 34 Sales 31
Jasper NULL Sales 31
Rafferty 31 Engineering 33
Jones 33 Engineering 33
Steinberg 33 Engineering 33
Smith 34 Engineering 33
Robinson 34 Engineering 33
Jasper NULL Engineering 33
Rafferty 31 Clerical 34
Jones 33 Clerical 34
Steinberg 33 Clerical 34
Smith 34 Clerical 34
Robinson 34 Clerical 34
Jasper NULL Clerical 34
Rafferty 31 Marketing 35
Jones 33 Marketing 35
Steinberg 33 Marketing 35
Smith 34 Marketing 35
Robinson 34 Marketing 35
Jasper NULL Marketing 35

交叉连接不会应用任何谓词去过滤结果表中的记录. 程序员可以用 WHERE 语句进一步过滤结果集.

外连接

An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table(s) one retains the rows from (left, right, or both).

(In this case left and right refer to the two sides of the JOIN keyword.)

No implicit join-notation for outer joins exists in standard SQL.

左外连接

The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the left table returns one row and the right table returns more than one matching row for it, the values in the left table will be repeated for each distinct row on the right table.

For example, this allows us to find an employee's department, but still shows the employee(s) even when their department does not exist (contrary to the inner-join example above, where employees in non-existent departments are excluded from the result).

Example of a left outer join, with the additional result row italicized:

SELECT *  
FROM   employee  LEFT OUTER JOIN department  
          ON employee.DepartmentID = department.DepartmentID
Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID
Jones 33 Engineering 33
Rafferty 31 Sales 31
Robinson 34 Clerical 34
Smith 34 Clerical 34
Jasper NULL NULL NULL
Steinberg 33 Engineering 33

右外连接

A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in A.

A right outer join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate).

For example, this allows us to find each employee and his or her department, but still show departments that have no employees.

Example right outer join, with the additional result row italicized:

SELECT * 
FROM   employee RIGHT OUTER JOIN department 
          ON employee.DepartmentID = department.DepartmentID
Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID
Smith 34 Clerical 34
Jones 33 Engineering 33
Robinson 34 Clerical 34
Steinberg 33 Engineering 33
Rafferty 31 Sales 31
NULL NULL Marketing 35

In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins (with the table order switched) and provide no additional functionality. The result above is produced also with a left outer join:

SELECT * 
FROM   department LEFT OUTER JOIN employee
          ON employee.DepartmentID = department.DepartmentID

全连接

A full outer join combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.

For example, this allows us to see each employee who is in a department and each department that has an employee, but also see each employee who is not part of a department and each department which doesn't have an employee.

Example full outer join:

SELECT *  
FROM   employee 
       FULL OUTER JOIN department 
          ON employee.DepartmentID = department.DepartmentID
Employee.LastName Employee.DepartmentID Department.DepartmentName Department.DepartmentID
Smith 34 Clerical 34
Jones 33 Engineering 33
Robinson 34 Clerical 34
Jasper NULL NULL NULL
Steinberg 33 Engineering 33
Rafferty 31 Sales 31
NULL NULL Marketing 35

Some database systems (like MySQL) do not support this functionality directly, but they can emulate it through the use of left and right outer joins and unions. The same example can appear as follows:

SELECT *
FROM   employee 
       LEFT JOIN department 
          ON employee.DepartmentID = department.DepartmentID
UNION
SELECT *
FROM   employee
       RIGHT JOIN department
          ON employee.DepartmentID = department.DepartmentID
WHERE  employee.DepartmentID IS NULL

SQLite does not support right join, so outer join can be emulated as follows:

SELECT employee.*, department.*
FROM   employee 
       LEFT JOIN department 
          ON employee.DepartmentID = department.DepartmentID
UNION
SELECT employee.*, department.*
FROM   department
       LEFT JOIN employee
          ON employee.DepartmentID = department.DepartmentID
WHERE  employee.DepartmentID IS NULL

自连接

A self-join is joining a table to itself.[2] This is best illustrated by the following example.

示例

A query to find all pairings of two employees in the same country is desired. If you had two separate tables for employees and a query which requested employees in the first table having the same country as employees in the second table, you could use a normal join operation to find the answer table. However, all the employee information is contained within a single large table. [3]

Considering a modified Employee table such as the following:

Employee Table
EmployeeID LastName Country DepartmentID
123 Rafferty Australia 31
124 Jones Australia 33
145 Steinberg Australia 33
201 Robinson United States 34
305 Smith United Kingdom 34
306 Jasper United Kingdom NULL


An example solution query could be as follows:

SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country
FROM Employee F, Employee S
WHERE F.Country = S.Country
AND F.EmployeeID < S.EmployeeID
ORDER BY F.EmployeeID, S.EmployeeID;

Which results in the following table being generated.

Employee Table after Self-join by Country
EmployeeID LastName EmployeeID LastName Country
123 Rafferty 124 Jones Australia
123 Rafferty 145 Steinberg Australia
124 Jones 145 Steinberg Australia
305 Smith 306 Jasper United Kingdom


For this example, note that:

  • F and S are aliases for the first and second copies of the employee table.
  • The condition F.Country = S.Country excludes pairings between employees in different countries. The example question only wanted pairs of employees in the same country.
  • The condition F.EmployeeID < S.EmployeeID excludes pairings where the EmployeeIDs are the same.
  • F.EmployeeID < S.EmployeeID also excludes duplicate pairings. Without it only the following less useful part of the table would be generated (for the United Kingdom only shown):
EmployeeID LastName EmployeeID LastName Country
305 Smith 305 Smith United Kingdom
305 Smith 306 Jasper United Kingdom
306 Jasper 305 Smith United Kingdom
306 Jasper 306 Jasper United Kingdom


Only one of the two middle pairings is needed to satisfy the original question, and the topmost and bottommost are of no interest at all in this example.

替换方式

The effect of outer joins can also be obtained using correlated subqueries. For example

SELECT employee.LastName, employee.DepartmentID, department.DepartmentName 
FROM   employee LEFT OUTER JOIN department 
          ON employee.DepartmentID = department.DepartmentID

can also be written as

SELECT employee.LastName, employee.DepartmentID,
  (SELECT department.DepartmentName 
    FROM department
   WHERE employee.DepartmentID = department.DepartmentID )
FROM   employee

实现

Much work in database-systems has aimed at efficient implementation of joins, because relational systems commonly call for joins, yet face difficulties in optimising their efficient execution. The problem arises because (inner) joins operate both commutatively and associatively. In practice, this means that the user merely supplies the list of tables for joining and the join conditions to use, and the database system has the task of determining the most efficient way to perform the operation. A query optimizer determines how to execute a query containing joins. A query optimizer has two basic freedoms:

  1. Join order: Because joins function commutatively and associatively, the order in which the system joins tables does not change the final result-set of the query. However, join-order does have an enormous impact on the cost of the join operation, so choosing the best join order becomes very important.
  2. Join method: Given two tables and a join condition, multiple algorithms can produce the result-set of the join. Which algorithm runs most efficiently depends on the sizes of the input tables, the number of rows from each table that match the join condition, and the operations required by the rest of the query.

Many join-algorithms treat their inputs differently. One can refer to the inputs to a join as the "outer" and "inner" join operands, or "left" and "right", respectively. In the case of nested loops, for example, the database system will scan the entire inner relation for each row of the outer relation.

One can classify query-plans involving joins as follows:[4]

left-deep
using a base table (rather than another join) as the inner operand of each join in the plan
right-deep
using a base table as the outer operand of each join in the plan
bushy
neither left-deep nor right-deep; both inputs to a join may themselves result from joins

These names derive from the appearance of the query plan if drawn as a tree, with the outer join relation on the left and the inner relation on the right (as convention dictates).

连接算法

Three fundamental algorithms exist for performing a join operation.

Nested loops

Use of nested loops produces the simplest join-algorithm. For each tuple in the outer join relation, the system scans the entire inner-join relation and appends any tuples that match the join-condition to the result set. Naturally, this algorithm performs poorly with large join-relations: inner or outer or both. An index on columns in the inner relation in the join-predicate can enhance performance.

The block nested loops (BNL) approach offers a refinement to this technique: for every block in the outer relation, the system scans the entire inner relation. For each match between the current inner tuple and one of the tuples in the current block of the outer relation, the system adds a tuple to the join result-set. This variant means doing more computation for each tuple of the inner relation, but far fewer scans of the inner relation.

Merge join

If both join relations come in order, sorted by the join attribute(s), the system can perform the join trivially, thus:

  1. Consider the current "group" of tuples from the inner relation; a group consists of a set of contiguous tuples in the inner relation with the same value in the join attribute.
  2. For each matching tuple in the current inner group, add a tuple to the join result. Once the inner group has been exhausted, advance both the inner and outer scans to the next group.

Merge joins offer one reason why many optimizers keep track of the sort order produced by query plan operators—if one or both input relations to a merge join arrives already sorted on the join attribute, the system need not perform an additional sort. Otherwise, the DBMS will need to perform the sort, usually using an external sort to avoid consuming too much memory.

Hash join

A hash join algorithm can only produce equi-joins. The database system pre-forms access to the tables concerned by building hash tables on the join-attributes. The lookup in hash tables operates much faster than through index trees. However, one can compare hashed values only for equality, not for other relationships.

See also

Notes

  1. ^ SQL Inner Join. www.SQLDatabaseTutorial.com. 
  2. ^ Shah 2005,第165頁
  3. ^ Adapted from Pratt 2005,第115–6頁
  4. ^ Yu & Meng 1998,第213頁

References

  • Pratt, Phillip J, A Guide To SQL, Seventh Edition, Thomson Course Technology, 2005, ISBN 9780619216740 
  • Shah, Nilesh, Database Systems Using Oracle - A Simplified Guide to SQL and PL/SQL Second Edition International Edition, Pearson Education International, 2005 [2002], ISBN 0131911805 
  • Yu, Clement T.; Meng, Weiyi, Principles of Database Query Processing for Advanced Applications, Morgan Kaufmann, 1998 [2009-03-03], ISBN 9781558604346