Transcript Table Joins

Brain Teaser
Who makes it, has no need of it.
Who buys it, has no use for it.
Who uses it can neither see nor feel it.
What is it?
Table Joins
WEB PROGRAMMING
Lesson Objectives
oTo understand how tables can be linked
oTo know how to use PHP to conduct a join in SQL
Recap
When we looked at databases previously we created the following two tables
Films
filmID
Directors
name
id
rating
name
description
country
yearRelease
director
genre
The link
So there’s a link between the two tables by using the ids.
In this case the id of the director is used in the films table under the director field
Films
filmID
Directors
name
id
rating
name
description
country
yearRelease
director
genre
1
LOTR –
Fellowship…
12A
Epic Story of…
2001
1
Fantasy
1
Peter Jackson
New Zealand
In Simple terms
When we create a link, we use numbers (ids) to link across two
tables.
Why do we need it?
The whole idea of linking is to stop redundancy, or repeating data
The big issue of redundancy is errors such as spelling mistakes,
and also having more data in the database than is required.
SQL
To get the information out of the database when the information we need is over two tables we need to use
an SQL join. Don’t worry it’s nice and easy, just follow the steps below.
Step 1
Step 2
Create a normal select statement
Add the second table you wish to link to
SELECT name, genre FROM film
SELECT name, genre FROM film, director
Step 3
Step 4
Add a WHERE section that makes the foreign key equal
to the primary key of the linking table
Specify the fields to the tables
SELECT name, genre FROM film, director WHERE director=id
SELECT film.name, film.genre, director.name FROM film,
director WHERE film.director=director.id
Example
Select all of the films from the database with all film information and the directors name.
SELECT
film.name, film.rating, film.description, film.yearRelease,
film.director, film.genre, director.name
FROM films, directors
WHERE film.director=directors.id