25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

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

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

152 ” Database Programming<br />

As you can see, we declare an inner join that creates a link between book and<br />

book_chapter; rows are returned only if a common value for the isbn column can<br />

be found for both tables.<br />

Note that inner joins only work well with assertive conditions—negative conditions<br />

often return bizarre-looking results:<br />

SELECT * FROM book INNER JOIN book_chapter ON book.isbn book_chapter.isbn;<br />

You would probably expect this query to return a list of all the records in the book<br />

table that do not have a corresponding set of records in book_chapter—however,<br />

the database engine returns a data set that contains an entry for each record in<br />

book_chapter that does not match each record in book; the end result is, in fact, a<br />

dataset that contains every line in book_chapter repeated many times over (the actual<br />

size of the set depending on the number of rows between the two tables that do<br />

have matching values for their respective isbn columns).<br />

Outer Joins<br />

Where inner joins restrict the results returned to those that match records in both tables,<br />

outer joins return all records from one table, while restricting the other table to<br />

matching records, which means that some of the columns in the results will contain<br />

NULL values. This is a powerful, yet sometimes confusing, feature of SQL database<br />

engines.<br />

Left joins are a type of outer join in which every record in the left table that matches<br />

the WHERE clause (if there is one) will be returned regardless of a match made in the<br />

ON clause of the right table.<br />

For example, consider the following SQL statement with a LEFT JOIN clause.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

SELECT book.title, author.last_name<br />

FROM author<br />

LEFT JOIN book ON book.author_id = author.id;<br />

The table on the left is the author table because it is the table included as the primary<br />

table for the statement in the FROM clause. The table on the right is the book table<br />

because it is included in the JOIN clause. Since this is a LEFT JOIN and there is no

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

Saved successfully!

Ooh no, something went wrong!