Detailed explanation of the execution process of mysql non-correlated subqueries and related subqueries

Some time ago, there was a SQL statement related to the sub-query. I didn't understand how it was executed and why the result appeared. Really tangled. Let's talk about the execution process of non-correlated sub-queries and related sub-queries.

Non-correlated subqueries

First look at a non-correlated subquery to the sql statement.

 

Requirement: Query the basic information of students with a score of 70 in the student table student and student grade table grade.

select t.sno,t.sname,t.sage,t.sgentle,t.sbirth,t.sdept from student t where t.sno in (select f.sno from garde f where f.score=70)

 

The execution of this sql statement is simple,

1. Find the student ID sno with a score of 70 in the grade table, and then return the student ID to the parent query as the condition of the where clause.

2. Find other basic information of the student with the student number in the student table.

Related subqueries

The so-called correlated sub-query means that solving the correlated sub-query cannot be the same as solving the ordinary sub-query. The sub-query is solved once, and then the parent query is solved. Since the inner query of the related subquery is related to the outer query, it must be repeatedly evaluated.

Let's look at the SQL statement of the related subquery.

Requirement: Find out the information of all students who have participated in the "Basic Computer" course and scored above 80 in the student table student and student transcript grade.

select t.sno,t.sname,t.sage,t.sgentle,t.sbirth,sdept from student t where 80<=(select f.score from grade f where f.sno=t.sno and f.cname='计算机基础')

The execution process of the subquery:

1. First take the sno value of the first record from the student table of the parent query, enter the subquery, and compare the conditions of its where clause "where f.sno=t.sno and f.cname='computer basic'" , If it matches, the score will be returned.

2. Return to the parent query, judge the where clause condition of the parent query is 80<= the score returned, and if the condition is true, return the first record.

3. Take out the second piece of data from the student table of the parent query and repeat the above operation until all records in the table in the parent query are retrieved.

to sum up: 

Comparing the sql execution process of these two queries, it can be seen that the difference between related sub-queries and non-correlated sub-queries is that related sub-queries depend on the parent query, and the parent query and the sub-query are related, especially in the where statement of the sub-query This is especially true in China. Understand their execution process, and then look at the code of the relevant subquery, and you will understand it all at once.

 

 

Guess you like

Origin blog.csdn.net/liuming690452074/article/details/114233365