:: DEVELOPER ZONE
MySQL extends the use of GROUP BY so that you can
use columns or calculations in the SELECT list
that don't appear in the GROUP BY clause. This
stands for any possible value for this group.
You can use this to get better performance by avoiding sorting and
grouping on unnecessary items. For example, you don't need to group
on customer.name in the following query:
mysql> SELECT order.custid, customer.name, MAX(payments)
-> FROM order,customer
-> WHERE order.custid = customer.custid
-> GROUP BY order.custid;
In standard SQL, you would have to add
customer.name to the GROUP BY
clause. In MySQL, the name is redundant if you don't run in ANSI
mode.
Do not use this feature if the columns you omit
from the GROUP BY part are not unique in the
group! You get unpredictable results.
In some cases, you can use MIN() and
MAX() to obtain a specific column value even if
it isn't unique. The following gives the value of
column from the row containing the smallest value
in the sort column:
SUBSTR(MIN(CONCAT(RPAD(sort,6,' '),column)),7)
See Section 3.6.4, “The Rows Holding the Group-wise Maximum of a Certain Field”.
Note that if you are using MySQL 3.22 (or earlier) or if you are
trying to follow standard SQL, you can't use expressions in
GROUP BY or ORDER BY clauses.
You can work around this limitation by using an alias for the
expression:
mysql> SELECT id,FLOOR(value/100) AS val FROM tbl_name
-> GROUP BY id, val ORDER BY val;
In MySQL 3.23 and up, aliases are unnecessary. You can use
expressions in GROUP BY and ORDER
BY clauses. For example:
mysql> SELECT id, FLOOR(value/100) FROM tbl_name ORDER BY RAND();
© 1995-2005 MySQL AB. All rights reserved.

User Comments
Warning: query failed: Unknown column 'user.firstname' in 'field list' in /data0/sites/live/web-main/lib/mysql-cxn.php on line 69
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /data0/sites/live/web-main/lib/docbook.php on line 245
Add your own comment.