Considerations for using MAX functions and Group By functions in MySQL

Source: Internet
Author: User

mysql> select * from test;+----+-------+------+-------+| id | name  | age  | class |+----+-------+------+-------+|  1 | qiu   |   22 |     1 | |  2 | liu   |   42 |     1 | |  4 | zheng |   20 |     2 | |  3 | qian  |   20 |     2 | |  0 | wang  |   11 |     3 | |  6 | li    |   33 |     3 | +----+-------+------+-------+6 rows in set (0.00 sec)

To find the largest age in each class, use group by and max.

If the following SQL statement is used, the output result is incorrect:

mysql> select id,name,max(age),class from test group by class;+----+-------+----------+-------+| id | name  | max(age) | class |+----+-------+----------+-------+|  1 | qiu   |       42 |     1 | |  4 | zheng |       20 |     2 | |  0 | wang  |       33 |     3 | +----+-------+----------+-------+3 rows in set (0.00 sec)
Although the age found is the largest age, the matched user information is not the actual information, but the basic information of the first record after group.

If I use the following statement for search, the actual results can be returned.

mysql> select * from (    -> select * from test order by age desc) as b    -> group by class;+----+-------+------+-------+| id | name  | age  | class |+----+-------+------+-------+|  2 | liu   |   42 |     1 | |  4 | zheng |   20 |     2 | |  6 | li    |   33 |     3 | +----+-------+------+-------+3 rows in set (0.00 sec)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.