Joins

12
Joins CIS-182

description

Introduction to Joins in SQL

Transcript of Joins

Page 1: Joins

Joins

CIS-182

Page 2: Joins

Multi-Table Queries

• Multi-table queries allow data from different tables to be combined and compared

• Typically done by comparing a common value– Comparison done between like data

types–May be primary key/foreign key fields

but doesn’t have to be

Page 3: Joins

Types of Multi-table Queries

• Joins: combine columns from multiple tables– Combine publishers and titles to show title and

publisher name

• Unions: combine rows from different lists – Create a list of editors and authors who live in

California

• Subqueries: use the results of one query to determine result of a second query– Find all books that have a higher than average

price

Page 4: Joins

Joins

• Inner Join: create a row for each match of values from two tables

• Outer Join: include all rows from one table and any related data found in a second table

• Cartesian Join: match each row in a table with every row in a second table– Also referred to as a cross join

Page 5: Joins

Inner Joins

• Most common kind of join• Get related data from two tables

where values match– Also referred to as an equi-join

• May be done using FROM clause or WHERE clause–Microsoft does not fully support WHERE

clause in SQL Server 2008

Page 6: Joins

Join With FROM

• Use the keyword JOIN with or without INNER preceeding it

• Specify the fields to compare using ON

• Field names that are not unique must be qualified by the table they’re in

Page 7: Joins

From Clause Examples

SELECT *FROM Publishers JOIN Titles ON Publishers.pub_id = Titles.pub_id

SELECT *FROM Publishers INNER JOIN TitlesON Publishers.pub_id = Titles.pub_id

Page 8: Joins

Join With WHERE

• List tables in FROM clause, separated by comma

• WHERE clause defines the fields to compare

Page 9: Joins

Where Clause Example

SELECT *FROM Publishers, Titles WHERE Publishers.pub_id =

Titles.pub_id

Page 10: Joins

Outer Joins

• Used when rows from one table should be part of the result even if there are no related rows in a second table– Create a list of all publishers, including any

titles the publisher has published

• Direction must be specified– Left/Right specify which table has the rows

which should always be included– Full specifies that rows from both tables

should be included even if no match

Page 11: Joins

Outer Join Example

• Include all publishers, even if they haven’t published a book:

SELECT *FROM Publishers LEFT OUTER JOINTitles ON Publishers.pub_id = Titles.pub_id

Page 12: Joins

Cartesian Join

• Match each row from table 1 with every row from table 2– Result is (table 1 row count)*(table 2 row count)

• May be done using CROSS JOIN

SELECT *FROM Publishers, Titles

SELECT *FROM Publishers CROSS JOIN Titles