Usage of mysqlhaving and groupby statements

Source: Internet
Author: User
Tags sorted by name
This article uses two simple examples to add restrictions to the group after groupby and query the number of repeated occurrences of a field in the data table. The havaing and groupby statements are sorted by the number of times.

This article uses two simple examples to add restrictions to the group after group by and query the number of repeated occurrences of a field in the data table. The havaing and group by statements are sorted by number of times.

You can use the aggregate function count (*) in Mysql to implement this function. For example, to query the records with the most frequently displayed names in the data table, you can group the records by group by name first, use count to calculate the number of entries in the group, and then sort by count:

The Code is as follows:

Name, count (*) from data group by name order by count (*) DESC limit 1

Data sorted by name will be returned without the limit of limit

Before using the aggregate function, we can use the where clause to add restrictions to the query. What if we need to add restrictions to the data in the group after group? The answer is having.

HAVING clause allows us to filter data of groups after grouping.
The WHERE clause filters records before aggregation, that is, before the group by clause and HAVING clause.
The HAVING clause filters group records after aggregation.

The having clause must contain data after group by and after order.

For example, after sorting names by appearance times in the previous article, we want to find only the data containing lin in the name, which can be written as follows:

The Code is as follows:

Select name, count (*) from data group by name having name like '% lin %' order by couny (*) DESC

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.