Você está na página 1de 1

84 Chapter 3: Selecting

Note: The detailed syntax for the <boolean_expression> is discussed later,


in Section 3.12, Boolean Expressions and the WHERE Clause. Even though
both ON and WHERE use the same <boolean_expression> syntax, ON condi-
tions dont often take advantage of all the features available. A typical ON
condition takes the form of ON a = b AND c = d to join tables using simple
equality relationships plus the AND operator. WHERE clauses, on the other hand,
tend to be more complex and thats why a full discussion of <boolean_expres-
sion> is deferred until Section 3.12.

The INNER JOIN operator combines every row in one table with every row in
the other table where the data in the two rows satisfies the ON condition. In this
example, the first parent row is combined with the first three child rows to pro-
duce a result set consisting of three rows.
parent. parent. child. child.
parent_key data_1 child_key parent_key
========== ======= ========= ==========
1 x 4 1 -- parent and child
1 x 5 1 -- parent and child
1 x 6 1 -- parent and child
The second and third parent rows dont appear in the final result set because
they cant be combined with any child rows and still satisfy the ON condition;
more specifically, parent.parent_key = 2 and 3 dont match any child.parent_key
values. The same is true of the fourth child row: It cant be matched with any
parent row because child.parent_key = NULL doesnt match any parent.par-
ent_key value. In other words, childless parent rows and orphaned child rows
arent included in the INNER JOIN using a foreign key relationship in the ON
condition.

3.4.3 LEFT OUTER JOIN


If you want to include all the rows in one or the other or both tables, even if
they dont satisfy the ON condition, you can use one of the OUTER JOIN oper-
ators. In the example from the previous section, the second and third rows from
the parent table could be included in the result set by using the LEFT OUTER
JOIN operator instead of INNER JOIN:
SELECT parent.parent_key,
parent.data_1,
child.child_key,
child.parent_key
FROM parent LEFT OUTER JOIN child ON parent.parent_key = child.parent_key
ORDER BY parent.parent_key,
child.child_key;
Heres how LEFT OUTER JOIN works: First, the INNER JOIN operation is
performed, as described earlier, to construct a result set. Then, any row in the
left-hand table that didnt participate in the INNER JOIN is appended to the
result set, with NULL values being used for the columns that would otherwise
come from the right-hand table. Note that the ON condition is only applied in
the first step, and is ignored in the second step.
In the example above, the LEFT OUTER JOIN appends two more rows to
the result set from the INNER JOIN, and these rows correspond to the second
and third rows from the parent table:

Você também pode gostar