Home Database Mysql Tutorial MySQL query statement complex query

MySQL query statement complex query

Mar 06, 2018 pm 03:37 PM
mysql complex Inquire

MySQL is a relational database management system. A relational database stores data in different tables instead of placing all data in one large warehouse, which increases speed and flexibility. There are often many complex queries in MySQL. In order to save everyone's time, the editor has summarized some commonly used complex queries.

MySQL complex query

1. Group query:

1. Keyword: GROUP BY

2. Usage: GROUP The BY statement is used in combination with the total function (such as SUM) to group the result set according to one or more columns. The total function often needs to be added GROUP BY statement.

The following are two tables, one is emp, the other is dept, we will operate the following queries on these two tables, as shown below:

First one: empTable

#Second picture: deptTable

##Now we query the total salary of each department of emp, the statement is as follows: ##SELECT deptno,SUM(sal)FROM emp GROUP BY deptno;

The results are as follows:

##Note: Here we query the total salary (sal) of each department, so it should be grouped according to the department number (deptno), so sum() is used for the sum;

##3. having:

where and having both make conditional judgments. Before introducing having, let’s take a look at the difference between where and having.

The function of where

is to remove the rows that do not meet the where condition before grouping the query results, that is, filter the data before grouping. The condition cannot contain the aggregate function , so use the where condition. Show specific rows.

having is used to filter the groups that meet the conditions, that is, filter the data after grouping. The conditions often include aggregate functions, use having Conditions display specific groups, or you can group using multiple grouping criteria.

For example: We want to query the department numbers whose total salary is greater than 10,000 in the emp table. The statement is as follows:

SELECT deptno,SUM(sal)FROM emp GROUP BY deptno HAVING SUM(sal)>10000;

##The results are as follows:

#In this way, it is found that the total salary is greater than The department number of 10,000 is 20, (the total salary is also displayed for understanding).

2. Join table query:

According to two The relationship between the columns in one or more tables, query data from these tables.

1, inner join(inner join(inner join(inner join) Connection):

Syntax: select field name 1, field name 2 from table1 [INNER] join table2 ON table1.Field name=table2.Field name;

##Note: Inner joins are deleted from the results All rows that do not have matching rows in other connected tables can only be queried for information that is owned by the connected tables, so the inner join may lose information, and inner can be omitted.

For example: we connect the two tables emp and dept, query ename and deptno, the statement is as follows: SELECT emp.ename,dept.deptno FROM emp INNER JOIN dept ON emp.deptno=dept.deptno;

Also A way to write: SELECT emp.ename,dept.deptno from emp,dept where emp.deptno=dept.deptno;



#Note: It turns out that there is a deptno of 40 in the dept table, but it is not there after the query. This is because there is no value of 40 in the deptno field in emp, so the dept table is automatically deleted when using innner join. Records with a deptno field value of 40.

2. Outer join:

2.1: Left outer join:

The result set retains all rows from the left table, but only contains rows from the second table that match the first table. The corresponding empty rows of the second table are put into NULL values.

2.2: Right outer join:The result set retains all rows from the right table, but only contains rows from the second table that match the first table. The corresponding empty rows of the second table are put into NULL values.

The left outer join and the right outer join can achieve the same effect by exchanging the positions of the two tables.

##Now we perform a query that uses grouping and join tables together

For example: We want to query the total salary of each department in emp and correspond to the department name in the dept table

Parse this sentence: The query field is sal (total salary) of each department in emp. Group query is used here, but the department name (dname) of the corresponding department is also queried. Since dname

is in the dept table, so we should connect the emp and dept tables.

Idea 1: We first query all the fields we need and then proceed Grouping, so connect first and then group, the statement is as follows:

SELECT e.deptno,d.dname,SUM(e.sal) FROM emp e INNER JOIN dept d ON e.deptno= d.deptno GROUP BY d.deptno;) (Note that the alias

is used here. The alias of emp is e, and the alias of dept is d)

Second way of writing:

SELECT e.deptno,d.dname,SUM(e.sal) FROM emp e ,dept d WHEREe.deptno=d.deptno GROUP BY d.deptno;

The results of these two writing methods are the same, as follows:



# Idea 2: We want to query the total salary of each department of emp, treat this result set as a table (here called table 1), and then let table 1 connect to the dept table Query the corresponding department name (dname);

Step 1: SELECT deptno,SUM(sal) FROM emp GROUP BY deptno; This statement queries the emp table The total salary of each department in , now we connect it with the dept

table:

Step 2: SELECT xin.*,d .dname FROM(SELECT deptno,SUM(sal) FROM emp GROUP BY deptno) xin INNER JOIN dept d ON xin.deptno

=d.deptno;This way you can query the desired The result, note that xin here is an alias, the result is as follows:



#The code here looks very long, but in fact the idea is very clear. Just treat the first query result as one table to connect to another table. This idea is not easy to make mistakes. If you practice writing more, you will become very skilled .

3. Paging:

Keywords: LIMIT

Syntax: select * from tableName condition limit current page number * page capacity -1, Page capacity;

Generally limit is used together with order by

For example, we want to query 5-10 in ascending order of department numbers in the emp table Records, each page displays 5 records, the statement is as follows:

SELECT *FROM emp ORDER BY deptno LIMIT 4,5;

In this way, you can query the desired results. Note that the last parameter 5 is the page capacity, which is the number of rows to be displayed on this page (that is, the record strip from the beginning to the end of this pagenumber).

For example, if we want to query 17 pages of records, each page will display 10 records:

LIMIT 17*10-1,10;

四:IN

##Keyword:In

If the return value of a subquery is more than one condition, IN must be used. "=";

## is not allowed. Note: LIMIT is always placed at the end .

Related recommendations:

How to solve the missing my.ini file in MySQL5.7

Summary of execution issues between mysql max and where

Detailed overview of MySQL statistics

The above is the detailed content of MySQL query statement complex query. 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.

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.

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.

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

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.

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