select orderid, orderdate, empid, custid
from sales.orders
where orderid =(selectmax(o.orderid)from sales.orders as o);
4.1.2 独立多值子查询
select orderid, orderdate, empid, custid
from sales.orders
where custid in(select c.custid
from sales.customers as c
where c.country ='USA');
不需要在多值子查询中使用distinct,数据库引擎可以自动删除重复值
4.2 相关子查询
4.2.1 相关子查询
select orderid, orderdate, empid, custid
from sales.orders as o1
where orderid =(selectmax(o2.orderid)from sales.orders as o2
where o1.custid = o2.custid);
4.2.2 exists
ANSI
只返回true或false
与in可以起到相同效果
区别
in为三值逻辑
当子查询返回结果中存在null
not in 得到 unknown
可能无法获得想要的结果
exists为二值逻辑
select custid, companyname
from sales.customers as c
where country ='Spain'andnotexists(select*from sales.orders as o
where o.custid = c.custid)
select custid, companyname
from sales.customers as c
where country ='Spain'and custid notin(select custid from sales.orders)
4.3 高级子查询
4.3.1 返回前一个或后一个记录
select orderid, orderdate, empid, custid,
(selectmax(o2.orderid)from sales.orders as o2
where o2.orderid < o1.orderid)as prevorderid
from sales.orders as o1;
4.3.2 连续聚合
累计求和
select orderyear, qty,(selectsum(o2.qty)from sales.ordertotalsbyyear as o2
where o2.orderyear <= o1.orderyear)as runqty
from sales.ordertotalsbyyear as o1
orderby orderyear;