MySQL query statement complex query
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:
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.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); 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 .
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.
