13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

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

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

252 Chapter 10 Working with Your <strong>MySQL</strong> Database<br />

Let’s look at a query that does all those things:<br />

select customers.name<br />

from customers, orders, order_items, books<br />

where customers.customerid = orders.customerid<br />

<strong>and</strong> orders.orderid = order_items.orderid<br />

<strong>and</strong> order_items.isbn = books.isbn<br />

<strong>and</strong> books.title like ‘%Java%’;<br />

This query returns the following output:<br />

+-----------------+<br />

| name |<br />

+-----------------+<br />

| Julie Smith |<br />

+-----------------+<br />

Notice that this example traces the data through four different tables, <strong>and</strong> to do this with<br />

an equi-join, you need three different join conditions. It is generally true that you need<br />

one join condition for each pair of tables that you want to join, <strong>and</strong> therefore a total of<br />

join conditions one less than the total number of tables you want to join.This rule of<br />

thumb can be useful for debugging queries that don’t quite work. Check off your join<br />

conditions <strong>and</strong> make sure you’ve followed the path all the way from what you know to<br />

what you want to know.<br />

Finding Rows That Don’t Match<br />

The other main type of join that you will use in <strong>MySQL</strong> is the left join.<br />

In the previous examples, notice that only the rows where a match was found<br />

between the tables were included. Sometimes you may specifically want the rows where<br />

there’s no match—for example, customers who have never placed an order or books that<br />

have never been ordered.<br />

One way to answer this type of question in <strong>MySQL</strong> is to use a left join.This type of<br />

join matches up rows on a specified join condition between two tables. If no matching<br />

row exists in the right table, a row will be added to the result that contains NULL values<br />

in the right columns.<br />

Let’s look at an example:<br />

select customers.customerid, customers.name, orders.orderid<br />

from customers left join orders<br />

on customers.customerid = orders.customerid;

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

Saved successfully!

Ooh no, something went wrong!