Using a Join to Control Query Output Order
Problem
You want to
sort a statement’s output using a characteristic of the
output that cannot be specified using ORDER
BY
. For example, you want to sort a set of rows by
subgroups, putting first those groups with the most rows and last
those groups with the fewest rows. But “number of rows in each
group” is not a property of individual rows, so you can’t use
it for sorting.
Solution
Derive the ordering information and store it in an auxiliary table. Then join the original table to the auxiliary table, using the auxiliary table to control the sort order.
Discussion
Most of the time when you sort a query result, you use an
ORDER
BY clause that names which column or columns
to use for sorting. But sometimes the values you want to sort by
aren’t present in the rows to be sorted. This is the case when you
want to use group characteristics to order the rows. The following
example uses the rows in the driver_log table to illustrate this. The
table contains these rows:
mysql>SELECT * FROM driver_log ORDER BY rec_id; +--------+-------+------------+-------+ | rec_id | name | trav_date | miles | +--------+-------+------------+-------+ | 1 | Ben | 2006-08-30 | 152 | | 2 | Suzi | 2006-08-29 | 391 | | 3 | Henry | 2006-08-29 | 300 | | 4 | Henry | 2006-08-27 | 96 | | 5 | Ben | 2006-08-29 | 131 | | 6 | Henry | 2006-08-26 | 115 | | 7 | Suzi | 2006-09-02 | 502 | | 8 | Henry | 2006-09-01 | 197 | | 9 | Ben | 2006-09-02 | 79 | | 10 | Henry | 2006-08-30 | 203 | ...