MySQL GROUP by doing grouped queries and sorting

Source: Internet
Author: User


So how do you solve the sorted output of the grouped data according to the DESC of the primary key?

There are two ways of answering:

1, the use of subqueries first sorted the table, and then the Word table for group by query, the resulting column will be the subquery obtained a record of the column.
2. Use the Max function to compare the columns that can calculate the maximum value, this method will only make the contrast column in accordance with DESC output, does not affect the other columns.

The results of these two methods are different and use them on demand.

With examples:

Table TAB1 has 3 columns: primary key ID, name, login time
ID Name time
1 A01 1
2 Www.111cn.net 2
3 A03 3
4 A02 4
5 A01 5
6 A04 6

Demand:

1, request to check out the number of users and the last landing time

Solution:

The first of these methods
Select Sub.name,count (sub.id) as login_nums,sub.time as Last_time
From (SELECT * from TAB1) Sub
GROUP BY Sub.name
Note: At this point, each column that the query obtains belongs to the same row of the original table, such as the ID of the specified query, and the ID of the row record with the latest time 111cn.net

The second method

Select Name,count (ID) as Login_nums,max (time) as Last_time
From TAB1
Group BY name
Note that each column that is being queried at this time is no longer part of the same row as the original table.

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.