MySQL Advanced Query and Programming Notes• [Chapter 3 Subqueries]

All chapters >>>>


Contents of this chapter

3.1 Subquery definition and single row subquery

3.1.1 Subquery definition

3.1.2 Single row subquery application

3.1.4 Practice exercises

3.2 Multi-line subquery application

3.2.1 in comparison operator

3.2.3 any|some keyword subquery

3.2.4 Practice exercises

3.3 Special applications of subqueries

3.3.1 Subqueries in the from clause

3.3.2 Subqueries in the select clause

3.3.4 Practice exercises

3.4 Subqueries in DML statements

3.4.1 Subqueries in the update clause

3.4.3 Practice exercises

to sum up:


3.1 Subquery definition and single row subquery

3.1.1 Subquery definition

Subquery (subquery) is an operation frequently used in databases. It is not only used in data query statements, but also in DML statements.

A subquery nests a query statement in another query statement. Under certain circumstances, the condition of a query statement needs another query statement to obtain, and the query result of the inner query statement can be provided for the outer query statement Query conditions

The essence of subquery: the query result of a select statement can be used as the input value of another statement. The subquery can be used not only in the where clause, but also in the from clause. At this time, the result of the subquery will be used as a temporary table (temporary table)

Subqueries can also appear in the select column of the select statement in the form of fields. According to the number of result rows returned by the subquery, it can be divided into single-row subquery and multi-row subquery

3.1.2 Single row subquery application

Single-row subquery means that the return result of the subquery has only one row of data. When referencing the result of a subquery in the conditional statement of the main query, you can use single-line comparison characters (such as =, >, <, >=, <= and <>) for comparison

Query the specific information of the "war" theme movie, and request the output of the title and director's name

Example:

(1) The movie (movie) table contains movie name, director name, and movie type number information, but does not contain movie type name information; the movie type (movie_type) table contains both movie type number information and movie type name information. The common information of the above two tables is the movie type number, so the movie table and the movie type table need to be connected when querying, and the movie type number is used as the connection between the two tables. First, query the movie genre number with the genre name "War" from the movie genre table, and use SQL1 as the mark

select id from movie_type where typeName=' 战争 '

(2) According to the area code queried by SQL1, retrieve the movie name and director name information in the movie table. Use SQL2 as a token, and substitute SQL1 as a query condition into SQL2

select movieName 电影名 ,director 导演名 from movie where typeId=
(select id from movie_type where typeName=' 战争 ')

Since typeName is the only constraint column in the movie_type table, the execution result of the subquery SQL1 can only have 1 (single-row subquery) or 0 records.

This example can also be realized by connecting query

select movieName 电影名 ,director 导演名 from movie m, movie_type mt
where m.typeId=mt.movie_type and typeName=' 战争 '

Example:

Query information about movies with fares higher than the average price, and output the name of the movie and director

(1) Get the average ticket price, use SQL1 mark

select avg(ticketPrice) from movie

(2) Query information about movies whose ticket price is greater than the average ticket price, and output the name of the movie and director. Use SQL2 markup and substitute SQL1 as query condition into SQL2

select movieName 电影名 ,director 导演名 from movie  where ticketPrice>( select avg(ticketPrice) from movie)

Example:

Query information about movies with higher ticket prices than "war", and request output of movie names and director names

(1) Query the movie genre number with the genre name "War" and use SQL1 to mark it

select id from movie_type where typeName=' 战争 '

(2) Query the average ticket price of "war" movies, use SQL2 markup, and substitute SQL1 as the query condition into SQL2 during execution

select avg(ticketPrice) from movie where typeID=(select id from movie_type where typeName=' 战争 ')

(3) Query information about movies whose ticket prices are greater than the average ticket price of “war” movies, and output the name of the movie and director. The query statement is marked with SQL3, and SQL2 is substituted into SQL3 as the condition when used

select movieName 电影名 ,director 导演名 from movie where ticketPrice>
(select avg(ticketPrice) from movie where typeID=(
select id from movie_type where typeName=' 战争 '))

The experience of subquery application is summarized as follows:

  • Subquery is generally used in the where clause of the select statement, and can be nested
  • The solution to writing complex sub-queries is to decompose the query layer by layer, that is, start from the innermost sub-query and split the nested SQL statements into independent SQL statements.
  • The execution process of the subquery follows the principle of "from the inside to the outside", that is, the innermost subquery is executed first, and then the execution result is merged with the outer statement, and then expanded layer by layer to form a complete SQL. Statement
  • Under normal circumstances, join query can be changed to sub-query implementation; but sub-query may not be changed to join query implementation
  • Comparison of execution efficiency of subquery and join query: When the number of rows of the subquery execution result is large, and the number of rows of the main query execution result is small, the subquery execution efficiency is higher; on the contrary, the execution efficiency of the join query is higher

3.1.4 Practice exercises

 

3.2 Multi-line subquery application

3.2.1 in comparison operator

When the multi-line comparison operator in is used, the main query will be compared with each value in the subquery, and if it is the same as any of the values, it will be returned. not in and in have the opposite meaning

Query related information about "war" and "comedy" movies, and request to output the title of the film and the director

Example:

(1) Query the genre numbers of movies whose genres are "War" and "Comedy"

select id from movie_type where typeName=' 战争 ' or typeName=' 喜剧 '

(2) Query related information about "war" and "comedy" movies

select movieName 电影名 ,director 导演名 from movie where typeID in
(select id from movie_type where typeName=' 战争 ' or typeName=' 喜剧 ')

Since the number of result rows returned by a multi-row subquery can be one, a single-row subquery is also a special case of a multi-row subquery, so the "=" comparator of a single-row subquery can be replaced with the "in" of a multi-row subquery Comparison operator. But you cannot replace the "in" comparator of a multi-line subquery with the "=" comparator of a single-line subquery.

Query the specific information of the movie booked by the customer "zhang01", request the output of the movie name, director name, ticket price, and film length, and sort them in ascending order of ticket price

Example:

(1) Query the customer number of the customer "zhang01"

select id from customer where username='zhang01'

(2) Query the sequence numbers of all movies booked by the customer "zhang01"

select scheduleId from ticket_sell where customerID in
(select id from customer where username='zhang01')

(3) Query the movie numbers of all movies booked by the customer "zhang01"

select movieId from `schedule` where id in (select scheduleId from ticket_sell where customerID in  (select id from customer where username='zhang01'))

(4) Query the specific information of the movie booked by the customer "zhang01"

select movieName 电影名 ,director 导演名 ,ticketPrice 票价(元),filmLength 片长(分钟)
from movie where id in(select movieId from `schedule` where id in
(select scheduleId from ticket_sell where customerID in
(select id from customer where username='zhang01'))) order by ticketPrice

This example is deeply nested, and if the join query is written, it will be relatively concise, especially when the number of product records is large, the efficiency of the join query will be higher. The SQL statement implemented using the connection query is as follows:

select distinct movieName 电影名 ,director 导演名 ,ticketPrice 票价(元),filmLength   片长(分钟) from movie m,`schedule` s,ticket_sell ts,customer c where m.id=s.movieId 
and  s.id=ts.scheduleId and ts.customerId=c.id and c.username='zhang01' order by ticketPrice

The implementation of the subquery in the above example well reflects the solution to the application of the subquery—the principle of "from inside to outside", that is, the main query including the subquery is generated layer by layer, and the main query generated layer by layer becomes The subqueries contained in the main query of the upper level are recursed in this order to finally generate the main query of the top level including all subqueries.

The all keyword is located after the multi-row comparison operator. The all keyword is used to compare the value of an expression or column with each row in a column of values ​​returned by the subquery, as long as the result of a comparison is false (false), The all test returns false and the main query is not executed; otherwise it returns true and the main query is executed

The meaning of the all operator is as follows:

  • When <all, it means less than the minimum value
  • When >all, it means greater than the maximum

grammar:

表达式或字段 多行比较运算符 all( 子查询 )

Query information about movies with higher ticket prices than all "comedy" movies, and output the title and director's name

Example:

(1) Query the genre number of the movie whose genre is "comedy"

select id from movie_type where typeName=' 喜剧 '

(2) Query the ticket prices of all "comedy" movies

select ticketPrice from movie where typeID=(
select id from movie_type where typeName=' 喜剧 ')

(4) Query movie information that has a higher ticket price than all "war" movies

select movieName 电影名 ,director 导演名 from movie where ticketPrice > all  (select ticketPrice from movie where typeID=(select id from movie_type where typeName=' 喜剧 '))

Since ">all (subquery)" means "greater than the maximum value returned by the subquery", you can also use the "> (maximum column value obtained by the subquery)" to solve the above example. The SQL statement is as follows:

select movieName 电影名 ,director 导演名 from movie where ticketPrice > (select max(ticketPrice) from movie where typeID=( select id from movie_type where typeName=' 喜剧 ' ))

3.2.3 any|some keyword subquery

any and some have the same query function

Before any or some is used in a subquery, use the any|some comparison operator to compare the value of an expression or column with each row in a column of values ​​returned by the subquery. As long as the result of a comparison is true, then If any or some test returns true, the main query is executed; otherwise the result is false, and the main query is not executed

The meaning of the any|some operator is as follows:

  • When <any|some, it means less than the maximum
  • When =any|some, it is equivalent to the in operator
  • When >any|some, it means greater than the minimum

grammar:

表达式或字段  多行比较运算符  any|some(子查询)

Query information about movies that have a higher ticket price than any "comedy" theme movie, and output the name of the movie and director

Example:

select movieName 电影名 ,director 导演名 from movie where ticketPrice > any
(select ticketPrice from movie where typeID=(
select id from movie_type where typeName=' 喜剧 '))

Since ">any (subquery)" means "greater than the minimum value of the results returned by the subquery", you can also use the "> (minimum column value obtained by the subquery)" to solve the above example. The SQL statement is as follows:

select movieName 电影名 ,director 导演名 from movie where ticketPrice > (select min(ticketPrice) from movie where typeID=( select id from movie_type where typeName=' 喜剧 ' ))

3.2.4 Practice exercises

 

3.3 Special applications of subqueries

3.3.1 Subqueries in the from clause

Subqueries are usually used in the where clause, but they can also be used in the from clause and select clause

Example:

The cinema online ticketing system optimizes the scientific nature of fare pricing in order to increase the attendance of movies. In order to understand the relationship between the ticket price of each movie and the overall ticket price of the movie in this category, it is more appropriate to display the average ticket price of each movie at the same time as the price of each movie.

select mt.typeName 电影类型 , m.movieName 电影名 , m.director 导演名 , round(m.ticketPrice,2)
票价(元), round(A.avgPrice,2) 该电影类型平均票价(元) from movie m, movie_type mt,
(select typeId,avg(ticketPrice) avgPrice from movie group by typeId) A where m.typeId=mt.id and m. typeId=A.typeId order by mt.id

3.3.2 Subqueries in the select clause

The use of sub-queries in the select clause, the essence of which is to use the execution results of the sub-query as the columns of the select clause, which can play the same role as the join query

Example:

Obtain the number of screenings and the number of screenings of films directed by Zhang Yimou

(1) Obtain the number of releases of films directed by Zhang Yimou

select count(*) 张艺谋所导演影片的上映数量 from movie where director=' 张艺谋 '

(2) Obtain the screening schedule of films directed by Zhang Yimou

select count(movieId) 张艺谋所导演影片的上映班次 from `schedule` where movieId in
(select id from movie where director=' 张艺谋 ')

(3) The query results obtained in (1) and (2), that is, the number of releases and the number of screenings of the films directed by Zhang Yimou are used as the query column of the select clause, and its form is the sub-query in the select clause.

select count(*) 张艺谋所导演影片的上映数量 , (select count(movieId) from `schedule` where
movieId in (select id from movie where director=' 张艺谋 ')) 张艺谋所导演影片的上映班次
from movie where director=' 张艺谋 '

exists is used to check whether the subquery will return at least one row of data. The subquery does not actually return any data, but returns the value true or false. exists specifies a subquery to detect the existence of rows. When the row of the subquery exists, the main query expression is executed, otherwise it is not executed

Query the names of all customers who booked movie tickets through the cinema online ticketing system

grammar:

主查询表达式  [not] exists ( 子查询 )

Example:

(1) The main query is used to obtain the customer name from the customer table.

(2) The subquery specified by exists will obtain any data satisfying the condition of "Customer Number = Customer Table. Customer Number" from the ticketing table.

(3) As long as there are data rows returned in the result set of the exists subquery, if the return result of the exists subquery is true, the main query will be executed to obtain the names of all customers who booked movie tickets; if the return result of the exists subquery is false, no Execute the main query. The final SQL statement is as follows:

select customerName 客户姓名 from customer c where exists
(select * from orders where customerID=c.customerID)

3.3.4 Practice exercises

 

3.4 Subqueries in DML statements

3.4.1 Subqueries in the update clause

  • Subqueries can not only be used in select statements to achieve nested query functions, but also maintain data and complete complex update, delete and insert functions
  • In order to complete the above data maintenance functions, subqueries need to be used in the update statement, delete statement and insert statement of the DML
  • The principle of using subqueries in DML statements is the same as using subqueries in select statements. Both use the results of the inner subquery as the reference value of the where condition in the outer main query.

Example:

In response to the government's call to enhance citizens' awareness and response capabilities to disasters, the theaters reduced the ticket prices of all disaster movies by 20%

(1) Get the movie genre number whose type is "disaster" in the subquery.

(2) In the main query, use the update statement to reduce the ticket price of all disaster movies by 20%

update product set currentPrice=currentPrice*0.9 where categoryID in(
select categoryID from category where categoryName=' 灾难 ')

Example:

Calculate the total amount of movie tickets booked by all customers, and use this amount to update the field value of the "cumulative booking amount" in the customer table

(1) In the ticketing table, group by customer number, and use "sum (actual fare)" to summarize the total booking amount of each customer

select customerID 客户编号 , sum(purchasePrice) 总订票金额(元) from ticket_sellgroup by customerID

(2) Because you want to assign the total booking amount of each customer summarized in (1) to the "cumulative booking amount" field in the customer table, you can use the SQL in (1) as a subquery and In the main query, execute "update customer table set accumulated ticket amount = (total ticket amount for each customer obtained in the subquery)".

(3) In order to implement the update statement, you need to delete the selection column "customer number" in the subquery, and in order to establish the association between the main query and the subquery, you also need to set "customer number = ticket table" in the where condition of the subquery. Customer Number"

update customer c set totalFee=(select sum(purchasePrice) from ticket_sell where customerID=c.ID group by customerID)

Use subquery to delete customer "chen01"

Example:

When deleting data, you need to consider the master-slave relationship of the table. The correct approach is to delete the data from the table first, and then delete the data from the main table.

(1) Use a subquery to delete all booking records of customer "chen01" in the ticketing table

delete from ticket_sell where customerID in
(select id from customer where username='chen01')

(2) Delete the record of customer "chen01" in the customer table

delete from customer where username='chen01'

3.4.3 Practice exercises

 

to sum up:

  • A subquery nests a query statement in another query statement. Under certain circumstances, the condition of a query statement requires another query statement to obtain
  • Before the comparison operator all keyword is used in a subquery, the keyword compares the value of an expression or column with each row in a column of values ​​returned by the subquery.
  • exists is used to detect the existence of rows. This subquery does not actually return any data, but returns true or false. When the row of the subquery exists, the main query expression is executed, otherwise it is not executed
  • The principle of using subqueries in DML statements is the same as using subqueries in select statements. Both use the results of the inner subquery as the reference value of the where condition in the outer main query.

 

Guess you like

Origin blog.csdn.net/weixin_44893902/article/details/111094651