Page 412 - Beginning PHP 5.3
P. 412
Part III: Using PHP in Practice
You can even sort by more than one column at once by separating the column names with commas:
mysql > SELECT favoriteGenre, firstName, lastName FROM members ORDER BY
favoriteGenre, firstName;
+---------------+-----------+-----------+
| favoriteGenre | firstName | lastName |
+---------------+-----------+-----------+
| crime | Jane | Field |
| crime | John | Sparks |
| horror | Marty | Pareene |
| thriller | Mary | Newton |
| romance | Jo | Scrivener |
| sciFi | Nick | Blakeley |
| nonFiction | Bill | Swan |
+---------------+-----------+-----------+
7 rows in set (0.00 sec)
You can read this ORDER BY clause as: “ Sort the results by favoriteGenre , then by firstName . ” Notice
how the results are ordered by genre, but where the genre is the same ( “ crime ” ), the results are then
sorted by firstName ( “ Jane ” then “ John ” ).
By default, MySQL sorts columns in ascending order. If you want to sort in descending order, add the
keyword DESC after the field name. To avoid ambiguity, you can also add ASC after a field name to
explicitly sort in ascending order:
mysql > SELECT favoriteGenre, firstName, lastName FROM members ORDER BY
favoriteGenre DESC, firstName ASC;
+---------------+-----------+-----------+
| favoriteGenre | firstName | lastName |
+---------------+-----------+-----------+
| nonFiction | Bill | Swan |
| sciFi | Nick | Blakeley |
| romance | Jo | Scrivener |
| thriller | Mary | Newton |
| horror | Marty | Pareene |
| crime | Jane | Field |
| crime | John | Sparks |
+---------------+-----------+-----------+
7 rows in set (0.00 sec)
Remember that ORDER BY works faster on a column that has an index, because indexes are already
sorted in order.
Using Pattern Matching for Flexible Queries
So far, all the WHERE clauses you ’ ve looked at have been fairly precise:
SELECT * from fruit WHERE name = ‘banana’;
SELECT * from fruit WHERE id > = 2;
374
9/21/09 9:11:58 AM
c13.indd 374
c13.indd 374 9/21/09 9:11:58 AM