sql的编写顺序
select .. from .. where .. group by ..having .. order by ..
sql的执行顺序
from .. where .. group by .. having .. select .. order by ..
关联子查询 :
在关联子查询中,对于外部查询返回的每一行数据,内部查询都要执行一次。另外,在关联子查询中是信息流是双向的。外部查询的每行数据传递一个值给子查询,然后子查询为每一行数据执行一次并返回它的记录。然后,外部查询根据返回的记录做出决策。
select * from dept d where exists(select * from emp e where = );
特点
1. 先执行外层查询
2. 再执行内层查询
非关联子查询:
非相关子查询是独立于外部查询的子查询,子查询执行完毕后将值传递给外部查询
select * from emp where sal = (select max(sal) from emp);
特点
1. 先执行内层查询
2. 再执行外层查询
所以你的例子里面,先执行外层的 select 语句的 from,把 Product 表里面每行数据查询出来,查询每一行数据,都要执行一次内层 select 语句,这个时候是完整的执行内层 select 语句,就是内层里面的 from … where … group by … select avg(sale_price),作用是把和外层查询出来的一行数据里面的 type 相同的所有行取出来,算sale_price列的平均值,然后继续执行外层的 where 条件,最后选出需要的列数据