MySQL GROUP BY data grouping--traps

Source: Internet
Author: User

GROUP by

The group BY keyword is used in MySQL to group one or some field queries and returns the first of the duplicate records.

Grammar:

SELECT column,... From Tb_name GROUP by column1,column2 ...

The user table is logged as follows:

UID username
1 Xiao Li
2 Xiao Zhang
3 Xiao Li
4 Xiao Wang
5 Xiao Li
6 Xiao Zhang

The user table above is queried as follows:

SELECT * from the user GROUP by username

The results of the returned query are as follows:

UID username
1 Xiao Li
2 Xiao Zhang
3 Xiao Wang
Description

The use of the GROUP by syntax in a MySQL database differs significantly from other databases. For standard SQL, group by must be used in conjunction with aggregate functions, and the selected field must appear in GROUP by In addition to the aggregate function. However, the functionality of GROUP by IS extended in MySQL:

    • Without an aggregate function, the result returned is the first row in the GROUP by result set, as shown in the example above.
    • When group by combines aggregate functions, the selected field does not have to exist in group by, and MySQL has the ability to suppress fields.

So we can easily get the desired query results based on MySQL's extended feature of GROUP by, combined with some other keywords such as ORDER by.

Example 2:

SELECT * from the user GROUP by Username,uid

The results of the returned query are as follows:

UID username
1 Xiao Li
3 Xiao Li
5 Xiao Li
2 Xiao Zhang
6 Xiao Zhang
4 Xiao Wang

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MySQL GROUP BY data grouping--traps

Related Article

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.