20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3<br />

96<br />

You’re one step further, but now you need to get rid of the MemberId and replace it with the members’<br />

first and last names. To do this, you need to link to the MemberDetails table and get the data from there,<br />

which involves a second INNER JOIN:<br />

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

FROM FavCategory INNER JOIN Category<br />

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

INNER JOIN MemberDetails<br />

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

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

The preceding code includes a second INNER JOIN statement after the first one. The ON statement links<br />

to the first INNER JOIN by linking the FavCategory and MemberDetails tables. The ORDER BY statement<br />

orders the results by last name and then first name to identify which member likes which categories.<br />

Note that if you’re using MS Access, you must change the <strong>SQL</strong> slightly. Access is happy with just one<br />

join but insists that you put brackets around each additional join. So the preceding code needs to be<br />

rewritten as follows:<br />

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

FROM (FavCategory INNER JOIN Category<br />

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

INNER JOIN MemberDetails<br />

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

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

Notice the brackets around the first inner join. The second inner join, which joins to the results of the<br />

first, doesn’t need brackets. Note that this code works on the other database systems but that the brackets<br />

aren’t required around the additional joins.<br />

The results so far are as follows:<br />

Category FirstName LastName<br />

Thriller Stuart Dales<br />

War Stuart Dales<br />

Historical Stuart Dales<br />

Horror William Doors<br />

Sci-fi William Doors<br />

Sci-fi Steve Gee<br />

War Jamie Hills<br />

Horror Jamie Hills<br />

Sci-fi Jamie Hills

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

Saved successfully!

Ooh no, something went wrong!