This is a correlated subquery.
You can think of it as a nested loop. For each row in the outer table, the subquery is run. And when it is run, the value of S1.GPA
is the value from the row in the outer query.
So, the subquery returns one or more rows that have a higher GPA. If there are no such rows, then the GPA
in the outer query is the highest one! Voila! One way to get the students with the maximum GPA.
Although you can understand the execution as a nested loop, the SQL optimizer does not need to use a nested loop to run such a query. For instance, if there is an index on Student(GPA)
then the query might be quite fast.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…