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.

Retrieving Data from the Database<br />

253<br />

This SQL query uses a left join to join customers with orders. Notice that the left join<br />

uses a slightly different syntax for the join condition; in this case, the join condition goes<br />

in a special ON clause of the SQL statement.<br />

The result of this query is<br />

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

| customerid | name | orderid |<br />

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

| 3 | Julie Smith | 1 |<br />

| 3 | Julie Smith | 4 |<br />

| 4 | Alan Wong | NULL |<br />

| 5 | Michelle Arthur | NULL |<br />

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

This output shows only those customers who have non-NULL orderids.<br />

If you want to see only the customers who haven’t ordered anything, you can check<br />

for those NULLs in the primary key field of the right table (in this case, orderid) because<br />

that should not be NULL in any real rows:<br />

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

from customers left join orders<br />

using (customerid)<br />

where orders.orderid is null;<br />

The result is<br />

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

| customerid | name |<br />

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

| 4 | Alan Wong |<br />

| 5 | Michelle Arthur |<br />

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

Also notice that this example uses a different syntax for the join condition. Left joins<br />

support either the ON syntax used in the first example or the USING syntax in the second<br />

example. Notice that the USING syntax doesn’t specify the table from which the join<br />

attribute comes; for this reason, the columns in the two tables must have the same name<br />

if you want to use USING.<br />

You can also answer this type of question by using subqueries.We look at subqueries<br />

later in this chapter.<br />

Using Other Names for Tables: Aliases<br />

Being able to refer to tables by other names is often h<strong>and</strong>y <strong>and</strong> occasionally essential.<br />

Other names for tables are called aliases.You can create them at the start of a query <strong>and</strong>

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

Saved successfully!

Ooh no, something went wrong!