13.09.2016 Views

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

Create successful ePaper yourself

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

Retrieving Data from the Database<br />

257<br />

select customerid, avg(amount)<br />

from orders<br />

group by customerid;<br />

When you use a GROUP BY clause with an aggregate function, it actually changes the<br />

behavior of the function. Instead of giving an average of the order amounts across the<br />

table, this query gives the average order amount for each customer (or, more specifically,<br />

for each customerid):<br />

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

| customerid | avg(amount) |<br />

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

| 1 | 49.990002 |<br />

| 2 | 74.980003 |<br />

| 3 | 47.485002 |<br />

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

Here’s one point to note when using grouping <strong>and</strong> aggregate functions: In ANSI SQL, if<br />

you use an aggregate function or GROUP BY clause, the only things that can appear in<br />

your SELECT clause are the aggregate function(s) <strong>and</strong> the columns named in the GROUP<br />

BY clause. Also, if you want to use a column in a GROUP BY clause, it must be listed in the<br />

SELECT clause.<br />

<strong>MySQL</strong> actually gives you a bit more leeway here. It supports an extended syntax,<br />

which enables you to leave items out of the SELECT clause if you don’t actually want<br />

them.<br />

In addition to grouping <strong>and</strong> aggregating data, you can actually test the result of an<br />

aggregate by using a HAVING clause. It comes straight after the GROUP BY clause <strong>and</strong> is<br />

like a WHERE that applies only to groups <strong>and</strong> aggregates.<br />

To extend the previous example, if you want to know which customers have an average<br />

order total of more than $50, you can use the following query:<br />

select customerid, avg(amount)<br />

from orders<br />

group by customerid<br />

having avg(amount) > 50;<br />

Note that the HAVING clause applies to the groups.This query returns the following<br />

output:<br />

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

| customerid | avg(amount) |<br />

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

| 2 | 74.980003 |<br />

+------------+-------------+

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

Saved successfully!

Ooh no, something went wrong!