20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Category FirstName LastName<br />

War Jenny Jones<br />

Thriller John Jones<br />

Romance Doris Night<br />

Historical Doris Night<br />

Thriller Susie Simons<br />

Horror Susie Simons<br />

Historical Susie Simons<br />

Romance Katie Smith<br />

War Katie Smith<br />

What you have at the moment is a results set that details each member’s favorite film categories. What<br />

you need, though, is a list of all the films under each category for each member. To produce such a list,<br />

you need to link to the Films table where all the film data is stored. The field that links the two tables is<br />

the CategoryId field, which was a primary key field in the Category table and a foreign key field in the<br />

Films table when you designed the database. You need to add the following INNER JOIN to the bottom<br />

of the current INNER JOIN list:<br />

INNER JOIN Films<br />

ON Films.CategoryId = Category.CategoryId<br />

Extracting Information<br />

This is the final link needed. It joins the Films table to the results and allows details such as FilmName<br />

and YearReleased to be included in the results:<br />

SELECT MemberDetails.FirstName, MemberDetails.LastName, Category.Category,<br />

FilmName, YearReleased<br />

FROM ((FavCategory INNER JOIN Category<br />

ON FavCategory.CategoryId = Category.CategoryId)<br />

INNER JOIN MemberDetails<br />

ON FavCategory.MemberId = MemberDetails.MemberId)<br />

INNER JOIN Films<br />

ON Films.CategoryId = Category.CategoryId<br />

ORDER BY MemberDetails.LastName, MemberDetails.FirstName;<br />

Note the brackets around the joins, which ensures that the code works with MS Access. The other<br />

database systems don’t need the brackets, and they can be left off. Notice also that the results of each join<br />

are bracketed. The first join is bracketed on its own, then this is bracketed together with the second join,<br />

and finally the third join links to these results and doesn’t need brackets<br />

The final <strong>SQL</strong> provides the following results set that details all the films in each member’s favorite film<br />

category:<br />

97

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!