Sorting Subsets of a Table

6.3.1 Problem

You don't want to sort an entire table, just part of it.

6.3.2 Solution

Add a WHERE clause that selects only the records you want to see.

6.3.3 Discussion

ORDER BY doesn't care how many rows there are; it sorts whatever rows the query returns. If you don't want to sort an entire table, add a WHERE clause to indicate which rows to select. For example, to sort the records for just one of the drivers, do something like this:

mysql> SELECT trav_date, miles FROM driver_log WHERE name = 'Henry'
 -> ORDER BY trav_date;
+------------+-------+
| trav_date | miles |
+------------+-------+
| 2001-11-26 | 115 |
| 2001-11-27 | 96 |
| 2001-11-29 | 300 |
| 2001-11-30 | 203 |
| 2001-12-01 | 197 |
+------------+-------+

Columns named in the ORDER BY clause need not be the same as those in the WHERE clause, as the preceding query demonstrates. The ORDER BY columns need not even be the ones you display, but that's covered later (Recipe 6.5).

Using the mysql Client Program

Writing MySQL-Based Programs

Record Selection Techniques

Working with Strings

Working with Dates and Times

Sorting Query Results

Generating Summaries

Modifying Tables with ALTER TABLE

Obtaining and Using Metadata

Importing and Exporting Data

Generating and Using Sequences

Using Multiple Tables

Statistical Techniques

Handling Duplicates

Performing Transactions

Introduction to MySQL on the Web

Incorporating Query Resultsinto Web Pages

Processing Web Input with MySQL

Using MySQL-Based Web Session Management

Appendix A. Obtaining MySQL Software

Appendix B. JSP and Tomcat Primer

Appendix C. References



MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net