SELECT EMPNO, LASTNAME FROM EMPLOYEE WHERE WORKDEPT ='A00' AND SALARY >(SELECTAVG(SALARY) FROM EMPLOYEE WHERE WORKDEPT ='A00')
相关子查询
1 2 3 4 5 6
SELECT E1.EMPNO,E1.LASTNAME, E1.WORKDEPT FROM EMPLOYEE E1 WHERE SALARY >(SELECTAVG(SALARY) FROM EMPLOYEE E2 WHERE E2.WORKDEPT = E1.WORKDEPT) ORDERBY E1.WORKDEPT
--answer: select orderid,orderdate,custid,empid from Sales.Orders where orderdate in ( selectmax(orderdate) from Sales.Orders ) /* 1.处理嵌套在外层查询语句里的子查询,应用max函数从表Sales.Orders中查找orderdate最后一天的日期,生成虚拟表VT1, 2.处理嵌套在外层的查询语句,从Sales.Orders表中查找满足where条件orderdate在虚拟表VT1中有相等值的数据,得到虚拟表VT2 3.处理select列表,从虚拟表VT2中查找出custid,orderdate,custid,empid返回虚拟表VT3 */
--answer: select empid,firstname,lastname from HR.Employees where empid notin( select o.empid from Sales.Orders as o where o.orderdate>='2008-05-01' ) /* 1.处理嵌套在外层查询语句里的子查询,表Sales.Orders别名o 2.查找满足where条件 o.orderdate>='2008-05-01',生成虚拟表VT1 3.从虚拟表VT1中处理select列表,查找出empid生成虚拟表VT2 4.处理嵌套在外层的查询语句,从Sales.Orders表中查找满足where条件empid不在虚拟表VT2中有相等值的数据,得到虚拟表VT3 5.处理select列表从虚拟表VT3中查找empid,firstname,lastname返回虚拟表VT4 */
--answer: SELECT custid, companyname FROM Sales.Customers AS C WHEREEXISTS (SELECT* FROM Sales.Orders AS O WHERE O.custid = C.custid ANDEXISTS (SELECT* FROM Sales.OrderDetails AS OD WHERE OD.orderid = O.orderid AND OD.ProductID =12)); /* 1.先处理外层查询,从Sales.Customers表别名C中取出一个元组,将元组相关列值custid传给内层查询 2.执行第一层内层查询,Sales.Orders表别名O中取出一个元组,将元组相关列值custid传给内层查询 3.执行第二层内层查询,Sales.Orders表别名OD应用where子句返回满足条件OD.orderid = O.orderid和 OD.ProductID = 12的值 4.返回到第一层内层查询中,应用where子句返回满足条件O.custid = C.custid和EXISTS条件的值 5.返回到外层查询处理 EXISTS,外查询根据子查询返回的结果集得到满足条件的行 */