[Database Principle] Relational Database Standard Language SQL and Relational Database Management System SQL Server (5)

Subquery.

When we WHEREinclude a SELECT...FROM...WHERE...query block in the form of a clause , this query block is called a subquery or a nested query, and the outer query statement that contains it is called a parent query. Nested queries can construct a series of simple queries into complex queries, enhancing the query capabilities. The nesting level of subqueries can reach up to 255 levels.
Nested queries are processed from inside to outside during execution. Each subquery is completed before the parent query at the next level is processed, and the parent query needs to use the results of the subquery.

Ordinary subquery.

The order of execution of ordinary subquery is: first execute the subquery, and then use the result of the subquery as the value of the query condition of the parent query. The ordinary subquery is executed only once, and all the records involved in the parent query are compared with its query results to determine the query result set.

  • [Ordinary subquery that returns one value] When the return value of the subquery is only one, you can use a comparison operator to connect the parent query and the subquery.

[Example] Query the number and name of the teacher with the same title as Teacher Liu Wei.

SELECT TNo,TN
FROM T
WHERE Prof = (SELECT Prof FROM T WHERE TN='刘伟')

This query is equivalent to dividing the query into two query blocks to execute, the first to be executed is the subquery:

SELECT Prof 
FROM T 
WHERE TN = '刘伟'

The sub-query returns a value, that is, teacher Liu Wei's title-"Lecturer", and then use this as the condition of the parent query, and then execute the parent query to find the teacher's number and name of the teacher.

  • [Ordinary subquery that returns a set of values] If the return value of the subquery is more than one, but a set, we cannot directly use comparison operators to express the query conditions, but need to use keywords ANYand ALL.

[Example] Query the name of the teacher who teaches course C5.

SELECT TN 
FROM T
WHERE TNo = ANY (SELECT TNo FROM TC WHERE CNo='C5')

First execute the subquery to find the set of teacher IDs of the teachers who teach the course C5, and then execute the parent query. As long as TNo is equal to any value in the result set of the subquery, it means that the teacher is teaching the course, and the corresponding TN is put Enter the final query result. Of course, this query can also be realized by connecting:

SELECT TN
FROM T,TC
WHERE T.TNo=TC.TNo AND CNo='C5'

[Example] Query the name and salary of teachers in other departments whose salary is higher than that of a teacher in the computer department.

SELECT TN,Sal
FROM T
WHERE Sal > ANY(
				   SELECT Sal FROM T WHERE Dept='计算机'
				 ) 
	  AND Dept!='计算机'

From a logical point of view, higher than the salary of a teacher in the computer department, only need to be higher than the minimum salary of the teacher in the computer department, so we can use the following code:

SELECT TN,Sal
FROM T
WHERE SaL > (SELECT MIN(Sal) FROM T WHERE Dept='计算机')
	  AND Dept!='计算机'

We first use the subquery and MIN()function to find the minimum salary x of the computer department, and then execute the parent query to find the name and salary of the teacher whose salary is higher than x among the teachers who are not in the computer department.

[Example] Query the name of the teacher who teaches course C5 and use keywords IN.

SELECT TN
FROM T
WHERE TNo IN(SELECT TNo FROM TC WHERE CNo='C5')

[Example] Query the names and salaries of teachers in other departments whose salary is higher than that of all teachers in the computer department.

SELECT TN,Sal
FROM T
WHERE Sal >ALL(SELECT SAL FROM T WHERE Dept = '计算机')
	  AND Dept!='计算机'

Like the above MIN()example of using library functions , we can also use library functions MAX()to achieve a higher salary than all computer teachers:

SELECT TN,Sal
FROM T
WHERE Sal >(SELECT MAX(Sal) FROM T WHERE Dept='计算机')
	  AND Dept!='计算机'

Related subqueries.

All the previous subqueries are ordinary subqueries, and there is no interaction between these subqueries and the parent query except that the parent query will use the results of the subquery as the query condition. However, sometimes the query conditions of a subquery need to refer to the attribute values ​​in the parent query table. We call this type of query a correlated subquery.
Compared with ordinary subqueries, the execution order of correlated subqueries is much more complicated. First, we select the first row of records in the parent query table, the internal subquery uses the related attribute values ​​in this row to query, and then the parent query determines whether this row meets the query conditions based on the results returned by the subquery. If the conditions are met, put this row into the query result set of the parent query. Repeat this process until each row of data in the parent query table is processed. From this we can also see that the number of executions of related sub-queries is determined by the number of rows in the parent query table.

[Example] Query the name of the teacher who does not teach course C5.

SELECT DISTINCT TN
FROM T
WHERE 'C5'!=ALL(SELECT CNo FROM TC WHERE TNo=T.TNo)

!=ALLThe meaning of is not equal to any value in the subquery result, and can also be used NOT INinstead. We describe the process of this correlation subquery based on the relationship table on page 27. First select a row in the parent relationship table T, which is the record [T1, Li Li, Male, 47, Professor, 1500, 3000, Computer], and then enter the subquery, and the CNo set found is {C1, C4}, C5 is not included, so the record meets the query conditions, we project it to the TN column, that is, the record [Li Li] enters the final result set. The subsequent process is the same. You can also
use EXISTSkeywords to perform related sub-queries, which EXISTSare quantifiers that indicate existence. Sub-queries with this keyword will not return any results, but a Boolean value of True or False.

[Example] Query the name of the teacher who teaches course C5 and use EXISTSkeywords.

SELECT TN
FROM T
WHERE EXISTS(SELECT * FROM TC WHERE TNo=T.TNo AND CNo='C5')

When a row in the TC table of the subquery meets the condition, the parent query will project the tuple in the T table to the TN column and put it into the result set.

[Example] Query the name of the teacher who did not teach course C5, and use EXISTSkeywords.

SELECT TN
FROM T
WHERE (NOT EXISTS(SELECT * FROM TC WHERE TNo=T.TNo AND CNo='C5'))

[Example] Query the names of students who have taken all courses.

SELECT SN
FROM S
WHERE NOT EXISTS
(
	SELECT *
	FROM C
	WHERE NOT EXISTS
	(
		SELECT *
		FROM SC
		WHERE SNo=S.SNo AND CNo=C.CNo
	)
)	 

Students who have taken all courses can also be understood as: For this student x, there is no such course y, and there is no record of the combination of <x,y> in the course selection table SC.
Data is added to the relationship table on page 27, so that there are indeed students who have taken all courses. The table is shown below. Student S1 has taken all 7 courses: The
Insert picture description here
execution results are as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44246009/article/details/108049756