Table of Contents
1. Aggregation query
1. Aggregation function (count, sum, avg...)
Use the GROUP BY clause to perform group queries on specific columns. Need to meet: When using GROUP BY for grouping query, the field specified by SELECT must be the "grouping by field", and other fields must be included in the aggregate function if they want to appear in SELECT.
2. Union query ((emphasis) multiple tables)
1.Inner join
2. Outer joins
3.Self-join
4. Subquery
5. Merge query
Home Database Mysql Tutorial Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

May 28, 2023 pm 09:31 PM
mysql

1. Aggregation query

1. Aggregation function (count, sum, avg...)

Common statistical totals, calculation of tie values ​​and other operations can be implemented using aggregate functions , common aggregate functions are:

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

  • ##Note that where and order by statements can be added at the end. These aggregate functions will query based on the result sets of these statements.

  • It is best not to use the following statements. Add limit, because MySQL's limit is different from the limit of other databases

  • When using aggregate functions of statistical columns, avoid writing other columns, otherwise this will happen When the first column is meaninglessly displayed

Example analysis of MySQL aggregation query and union query operations

Note:

1. count: You can use count (*), count (0), count (1). To put it bluntly, it is actually the same as selecting 1 from the entire table. The 0 and 1 in this count are just passed in as parameters. , first select 1, and then count the value of count

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations##2.sum, max, Neither min nor avg can be passed in *, fields or expressions must be passed in using

3. avg can be combined with sum, and multiple aggregate functions can be used together

2. GROUP BY clause

Use the GROUP BY clause to perform group queries on specific columns. Need to meet: When using GROUP BY for grouping query, the field specified by SELECT must be the "grouping by field", and other fields must be included in the aggregate function if they want to appear in SELECT.

    The aggregation function after Select is executed after Group by has completed the grouping.
  • The essence of the Group by statement is grouping, and it is often used with Aggregation query uses
  • syntax:

Example analysis of MySQL aggregation query and union query operations

##The field specified by Select must be after group by Yes and no can only appear in aggregate functions, otherwise problems will occur Example analysis of MySQL aggregation query and union query operations

GROUP BY Notes

1. The essence of the Group by statement is grouping, often Use it with aggregate query

2. As long as there is an aggregate function, it may be grouped

3. In the grouping operation, the query allows grouping fields and aggregate functions, and other non-grouping fields need to be guaranteed There are no multiple rows after grouping (such as student ID grouping, the query field can have student names, because after student ID grouping, there is only one row)

4. Use where to filter conditions before grouping, and use having after grouping (the code is the order Execution)

Execution order: from > on> join > where > group by > with > having >select > distinct > order by > limit

The execution starts from from first, so aliases are generally named here. You can also name them in select, but select is executed later and the front is named. None of those places are used for execution.
  • Limit is always executed at the end
  • 5.---select classid, average(score) from student where score>60 group by classid havinng classid
First find the rows with score > 60, and then group them according to classid. From the obtained results, select the rows with class 6.group by is to merge repeated rows into one row

7.group by when there are many fields , may not be merged, but the effect of grouping is achieved, and aggregate functions can be used.

3.HAVING

After grouping by the GROUP BY clause, when you need to conditionally filter the grouped results, you cannot use the WHERE statement, but need to use HAVING. HAVING is executed after GROUP BY

Example analysis of MySQL aggregation query and union query operations

2. Union query ((emphasis) multiple tables)

1.Inner join

Syntax:

Example analysis of MySQL aggregation query and union query operations

You may not be able to distinguish the difference between the connection conditions and the filtering result set conditions in the second method. You can use either one, but give priority to the first one, in order to correspond to the subsequent outer joins. Inner join is equivalent to giving the connection condition on the obtained Cartesian product

Example analysis of MySQL aggregation query and union query operations

If group by is not used here, there will be only one line like the following, which is equivalent to Add up all the scores of all students. Since what we need is the total score of each student, we need to group them according to the student ID first.

Example analysis of MySQL aggregation query and union query operations

2. Outer joins

Outer joins are divided into left outer joins and right outer joins. The left outer join is a connection method when the table on the left is completely displayed when a joint query is performed; the right outer join is a connection method when the table on the right is fully displayed when a joint query is performed.

Note:

  • Left join: The data in the left table will not be based on the joining condition (the part after on, including the and) Filter and display all, other conditions can still be filtered, such as adding where and other conditions later.

  • If there is data in the right table with values ​​that do not meet the connection conditions, the data in the right table will display null and the left table will display all

Syntax: (Note: On can also be followed by where)

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

The same query method, this time it can show that the 8th place result is For empty student information, all the data in the left table, that is, the student table, will be displayed and will not be affected by the connection condition stu.id = sco.student_id. If it is within the previous When connecting , cannot display the information of the student "Foreigner Learning Chinese" , because there is no ID of the student "Foreigner Learning Chinese" in the sco table.

3.Self-join

Self-join refers to querying by connecting itself in the same table.

Usage scenario: Compare multiple rows in the same table.

Note: Self-join queries can also be queried using the join on statement.

Example analysis of MySQL aggregation query and union query operations

4. Subquery

Subquery refers to a select statement embedded in other sql statements, also called a nested query

Query and classmates of "do not want to graduate" students: (self-join)

Example analysis of MySQL aggregation query and union query operations

Multi-row subquery: subquery that returns multiple rows of records (used frequently)

Case: Query the score information of "Chinese" or "English" courses: (internal connection)

Example analysis of MySQL aggregation query and union query operations

Example analysis of MySQL aggregation query and union query operations

group by here It does not play a role in merging, but it plays a role in grouping

Example analysis of MySQL aggregation query and union query operations

5. Merge query

In practical applications, in order to merge the execution of multiple selects As a result, the set operators union, union all can be used. When using UNION and UNION ALL, the fields in the result sets of before and after the query must be consistent.

**In some cases, multiple tables cannot be related, but you need to query data in the same field

**Union is more efficient than or

  • union

This operator is used to obtain the union of two result sets. This operator will automatically eliminate duplicate rows in the result set, and will automatically deduplicate when the data content is exactly the same.

Case: Query courses with ID less than 3, or courses named "English":

Example analysis of MySQL aggregation query and union query operations

  • union all

This operator is used to obtain the union of two result sets. When this operator is used, duplicate rows in the result set are not removed. (When the data obtained is exactly the same, it will be displayed and no duplication will be performed)

Case: Query for courses with an ID less than 3 or with the name "Java"

Example analysis of MySQL aggregation query and union query operations

The above is the detailed content of Example analysis of MySQL aggregation query and union query operations. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles