foreword
Last time we talked about the basic query of the database, this time we will continue with the advanced query of the database. Advanced query is based on basic query. If you haven't read it, it is recommended that you learn basic database query first.
Portal: Basic query of MySQL database
The query of the database is the focus of the database learning part, and the advanced query of the database is even more important. Everyone should pay attention to a lot of practice before they can master it better.
content
build table
In the basic query, we have already built the table, but the advanced query part of the database involves the query of multiple tables. Therefore, we need to build the table again, so that we can better understand and remember in the learning process.
Let's create the student table first
create table t_student(
id INT PRIMARY KEY NOT NULL,
name VARCHAR(4) NOT NULL,
age INT NOT NULL,
sex CHAR(1) NOT NULL,
class VARCHAR(10) ,
birthplace varchar(10),
id_teach INT UNSIGNED NOT NULL
);
#DROP TABLE t_student;
INSERT INTO t_student VALUES('88201','张三',18,'男','软件211','浙江杭州',689);
INSERT INTO t_student VALUES('88202','李四',19,'男','软件212','河南郑州',898);
INSERT INTO t_student VALUES('88203','小红',18,'女','计算机211','北京',758);
INSERT INTO t_student VALUES('88204','王五',16,'男','软件214','浙江杭州',589);
INSERT INTO t_student VALUES('88205','小蓝',17,'女','计算机212','江苏常州',988);
INSERT INTO t_student VALUES('88206','小王',20,'男','软件211','北京',689);
INSERT INTO t_student VALUES('88207','张四',18,'男','计算机211','江苏常州',758);
Output:
create teacher table
CREATE TABLE t_teach(
id INT PRIMARY KEY NOT NULL,
name VARCHAR(10) NOT NULL,
age INT ,
sex CHAR(1) ,
birthplace varchar(10)
);
Output:
Build grade sheet:
CREATE TABLE t_grade(
id INT PRIMARY KEY NOT NULL,
chinese INT UNSIGNED,
english INT UNSIGNED,
java INT UNSIGNED,
python INT UNSIGNED
);
Output:
The table construction is completed. These three tables are related to a certain extent. We will use these three tables to learn the advanced query part of the MySQL database.
Aggregate function
Aggregate functions are often used in MySQL database data processing, such as minimum, maximum, and summation.
The commonly used aggregation functions of MySQL database are explained in detail as follows:
AVG(col)
: Returns the average of the
COUNT(col)
specified column: Returns the number of non-NULL values in the
MIN(col)
specified column: Returns the minimum value of the
MAX(col)
specified column: Returns the maximum value
SUM(col)
of the specified column: Returns the sum of all values of the specified column
GROUP_CONCAT
: Returns the column values that belong to a group The result of the combination of connections
Use the format:
SELECT COUNT(字段名) FROM 表名;
SELECT MAX(字段名) FROM 表名;
SELECT MIN(字段名) FROM 表名;
SELECT SUM(字段名) FROM 表名;
Example: Who has the highest overall grade in the class?
SELECT id,MAX(chinese+english+java+python) AS count_grade
FROM t_grade;
output:
Group query
GROUP BY
It is grouping, grouping is not deduplication, the query results are grouped by one or more, and the fields with the same value are the same group
The format is as follows:
SELECT 字段名1,字段名2,… FROM 表名 GROUP BY 字段1,字段2,..
GROUP BY
The following fields are the fields on which the grouping is based, first grouping according to field 1, then grouping again according to field 2, and so on...
Example: group by class
SELECT class,GROUP_CONCAT(name)
FROM t_student GROUP BY class;
output:
having clause
HAVING
Clauses are oftenGROUP BY
used in conjunction with clauses in aSELECT
statementHAVING
to specify filter conditions for a set of rows or aggregates to filter groupings based on the specified conditions.
If a clause is omitted GROUP BY
, the HAVING
clause behaves like a WHERE
clause. but,HAVING
Clauses allow us to filter various data after grouping。WHERE
clause to filter records before aggregation, that is, before GROUP BY
the HAVING
ampersand. Whereas the HAVING
clause filters the group records after aggregation. My understanding is that there is no such data in the real table, these data are generated by some functions.
That is to say, both HAVING
clauses and WHERE
clauses can be queried with conditions, but WHERE
the conditions in the clauses cannot include aggregate functions, but the HAVING
clauses can.
At this time, some people may want to say that since both of them can perform conditional queries, and the function of clauses is more powerful HAVING
than that of clauses, why do we need to learn clauses?WHERE
WHERE
The clause to be noted here is WHERE
executed before the SELECT
clause, and the clause is HAVING
executed after the SELECT
clause. If we use WHERE
the clause, we can filter out a large part of the data first, which requires a faster query speed HAVING
. Then the query speed is relatively slow, so it is not an optimal query program.
Use the following format:
SELECT 字段名1,字段名2,…
FROM 表名
GROUP BY 字段
HAVING 筛选条件;
Example: Classes with an average age of 18 and above
SELECT class,GROUP_CONCAT(name)
FROM t_student
GROUP BY class
HAVING AVG(age)>=18;
output;
table join query
When we query data, the data we often need is in different tables. At this time, we need to connect the tables together to perform multi-table query. Table join query is divided into: inner join query, outer join query, natural join query
Next, we learn them in turn
Inner join query
Inner join is a cross join that removes some data rows in the query result set by setting join conditions in the query. Simply put, it is to use conditional expressions to eliminate certain data rows that are cross-connected.
FROM
Use the keyword INNER JOIN
or in the MySQL clause to JOIN
join two tables, and use the ON
clause to set the join condition. Inner join is the default table join of the system, so FROM
the INNER
keyword can be omitted after the clause, and only the keyword can be used JOIN
. After using an inner join, the FROM
clause in the ON
clause can be used to set the conditions under which the tables are joined.
Connection format:
SELECT 字段名1,字段名2,…
FROM 表名1 JOIN 表名2...
ON 连接条件;
Example:
SELECT *
FROM t_student AS s JOIN t_teach AS t
ON s.id_teach=t.id;
Output:
There is also an implicit way of writing inner joins:
SELECT 字段名1,字段名2,…
FROM 表名1,表名2...
WHILE 连接条件;
The effect is the same, but it is easy to forget the conditions when writing, so it is not recommended to use this.
Outer join query
The outer join query is divided into: left join query and right join query. The left join query means that the left table is used as the main table, and the data of the main table is used as the benchmark to match the data of the right table. If it matches, it will be displayed, and if it does not match, it will be displayed as NULL;
Left outer join query LEFT OUTER JOIN
, in MySQL can be abbreviated as LEFT JOIN
;
right outer join query RIGHT OUTER JOIN
, MySQL can be abbreviated as RIGHT JOIN
;
SELECT 字段名1,字段名2,…
FROM 表名1 LEFT|RIGHT JOIN 表名2...
ON 连接条件;
Example:
SELECT *
FROM t_student AS s LEFT JOIN t_teach AS t
ON s.id_teach=t.id;
Output:
Example:
SELECT *
FROM t_student AS s RIGHT JOIN t_teach AS t
ON s.id_teach=t.id;
Output:
Here we introduce a keyword UNION, which can combine the query results of multiple SQL statements into a result set. as follows:
SELECT *
FROM t_student AS s JOIN t_teach AS t
ON s.id_teach=t.id
UNION
SELECT *
FROM t_student AS s RIGHT JOIN t_teach AS t
ON s.id_teach=t.id;
output:
natural join query
The self-join query is the join query between the current table and itself. The key point is to virtualize a table to an alias. The self-join query is generally used as the value of a field in the table to refer to the value of another field.
Example:
SELECT t1.id,t1.java
FROM t_grade AS t1 JOIN t_grade AS t2
ON t1.java=t2.java
HAVING t1.java>=AVG(t2.java);
output:
subquery
Subqueries allow one query to be nested within another query. Subqueries, also known as inner queries, are compared to inner queries, and those that contain inner queries are called outer queries. A subquery can contain any clause that a normal SELECT can include, nested within a SELECT, SELECT...INTO statement, INSERT...INTO statement, DELETE statement, or UPDATE statement or within another subquery.
In the SELECT clause, the sub-query is calculated first, and the sub-query result is used as the filter condition of another query in the outer layer. The query can be based on one table or multiple tables.
Commonly used operators in subqueries
IN subquery
The subquery used in conjunction with the keyword IN is mainly used to determine whether a given value exists in the result set of the subquery. Its syntax format is:
<表达式> [NOT] IN <子查询>
The syntax is explained below.
<表达式>
: Used to specify an expression. When the expression is equal to a value in the result set returned by the subquery, it returns TRUE, otherwise it returns FALSE; if the keyword NOT is used, the returned value is just the opposite.
<子查询>
: Used to specify a subquery. The subquery here can only return one column of data. For more complex query requirements, you can use the SELECT statement to achieve multi-level nesting of subqueries.
Comparison operator subqueries
The subquery used by the comparison operator is mainly used to compare the value of the expression with the value returned by the subquery. Its syntax format is:
<表达式> {
= | < | > | >= | <= | <=> | < > | != }
[ ALL | SOME | ANY]<子查询>
The syntax is explained below.
<子查询>
: Used to specify a subquery.
<表达式>
: Used to specify the expression to be compared.
ALL、SOME 和 ANY
: Optional, used to specify restrictions on comparison operations.
- The keyword
ALL
is used to specify that the expression needs to be compared with each value in the subquery result set. When the expression and each value satisfy the comparison relationship, it will return TRUE, otherwise it will return FALSE; - The keywords
SOME
andANY
are synonyms, indicating that as long as the expression satisfies the comparison relationship with a value in the subquery result set, it returns TRUE, otherwise it returns FALSE.
EXIST subquery
The subquery used by the keyword EXIST is mainly used to judge whether the result set of the subquery is empty. Its syntax format is:
EXIST <子查询>
Returns TRUE if the result set of the subquery is not empty; otherwise returns FALSE.
subquery classification
There are the following types of subqueries:
1. Scalar subquery: Returns a scalar of a single value, the simplest form.
2. Column subquery: The returned result set is N rows and one column.
3. Row subquery: The returned result set is one row and N columns.
4. Table subquery: The returned result set is N rows and N columns.
Scalar subquery : It means that the subquery returns a scalar with a single value, such as a number or a string. It is also the simplest return form in a subquery. The scalar results of subqueries can be compared using the operators = > < >= <= <>, usually on the right side of the comparison.
MySQL column subquery : Refers to the result set returned by the subquery is N rows and one column, because the result set returned by the column subquery is N rows and one column, so you cannot directly use = > < >= <= <> these operators to compare scalar results. IN, ANY, SOME and ALL operators can be used in column subqueries
MySQL row subquery : Row subquery means that the result set returned by the subquery is one row and N columns. The result of the subquery is usually the result set returned by querying a row of data in the table. Similarly, you cannot directly use = > < >= <= <> These operators compare scalar results.
MySQL table subquery : It means that the result set returned by the subquery is a table data with N rows and N columns. Similarly, you cannot directly use = > < >= <= <> operators to compare scalar results.
Example: Who are the students whose teachers are from Beijing?
SELECT id,name
FROM t_student
WHERE id_teach=
(SELECT id
FROM t_teach
WHERE birthplace="北京");
Output:
Example: Which students have the same birthplace as the teacher?
SELECT id,name,birthplace
FROM t_student
WHERE birthplace = ANY
(SELECT birthplace
FROM t_teach);
output:
Epilogue
This is the end of our explanation of the MySQL database, but the learning is not over, we have to keep practicing, only in this way can we skillfully use them for office work in the future!
Next notice: MySQL's basic operations on data
Continually updated…