Professional Documents
Culture Documents
JOINS
• Example:
How to work with tables from
different databases
How to use compound
join conditions
• A join condition can include 2 or more conditions by
using AND, OR
• Condition in ON run before data join and condition
in WHERE run after data joined
EmployeeName ManagerName
Alan Shearer John Smith
Golden Brown Alan Shearer
David Kan Alan Shearer
How to work with outer joins
15/31
Introduction to outer join
• Inner Joins are the most common type of
join. But MySQL support outer join.
• Outer Joins retrieves all rows of that
satisfy the join condition, plus unmatched
rows in the left or right table.
• There are 3 types of outer joins:
– LEFT JOIN
– RIGHT JOIN
– FULL JOIN
How to code an outer join
Outer join examples
Outer joins that join more than
two tables
Other skills for working with joins
This session use USING and NATURAL
keywords and cross join.
How to join tables with the
USING keyword
• If the column join are same name in both join table.
You can use USING keyword to simplify the syntax
for join statement.
• Example:
SELECT invoice_number, vendor_name
FROM vendors
JOIN invoices USING(vendor_id)
ORDER BY invoice_number
How to join tables with the
NATURAL keyword
• The NATURAL keyword is used to create a natural
join that joins two tables based on all columns in
the two tables that have the same name.
• Example:
SELECT
department_name,last_name,project_name
FROM departments
NATURAL JOIN employees
LEFT JOIN projects USING(vendor_id)
ORDER BY department_name
How to use cross joins
• A cross join joins each row from the first table with
each row from the second table.
• Example:
SELECT d.department_number,department_name,
employee_id,last_name
FROM departments d
CROSS JOIN employees
ORDER BY d.department_number
How to work with unions
The syntax of a union
• Same number of columns
• Same columns name, data types
SELECT column_list FROM table1
UNION
SELECT column_list FROM table2
• Default: eliminates duplicate rows
• ALL keyword: include duplicate rows
Unions that combines result set
from the different tables
Unions that combines result set
from the same table
Summary
• INNER JOIN
• OUTER JOIN
• UNION