第4章 子查询
4.2.1 Exist 谓语:
use TSQLFundamentals2008 select * from Sales.Customers as C where c.country=N'Spain' select * from Sales.Customers as C where c.country=N'Spain' and exists(select * from Sales.Orders as O where o.custid=C.custid) select * from Sales.Customers as C where c.country=N'Spain' and not exists(select * from Sales.Orders as O where o.custid=C.custid)
4.3.2 连续聚和
select OBJECT_ID('Sales.OrderTotalsByYear') if OBJECT_ID('Sales.OrderTotalsByYear') is not null drop view Sales.OrderTotalsByYear go create view Sales.OrderTotalsByYear with schemabinding as select YEAR(o.orderdate) as orderyear, SUM(od.qty) as qty from Sales.Orders as o join Sales.OrderDetails as od on o.orderid=od.orderid group by YEAR(o.orderdate) go
查询:
select O1.orderyear, o1.qty, (select SUM(o2.qty) from Sales.OrderTotalsByYear as o2 where o2.orderyear <= o1.orderyear ) as runqty from Sales.OrderTotalsByYear as O1 order by o1.orderyear
4.3.3 行为不当的子查询
SELECT custid, companyname FROM Sales.Customers AS C WHERE custid NOT IN(SELECT O.custid FROM Sales.Orders AS O);
返回:
custid companyname
22 Customer DTDMN
57 Customer WVAXS
插入一条custid=NULL的记录:
INSERT INTO Sales.Orders (custid, empid, orderdate, requireddate, shippeddate, shipperid, freight, shipname, shipaddress, shipcity, shipregion, shippostalcode, shipcountry) VALUES(NULL, 1, '20090212', '20090212', '20090212', 1, 123.00, N'abc', N'abc', N'abc', N'abc', N'abc', N'abc');
SELECT custid, companyname FROM Sales.Customers AS C WHERE custid NOT IN(SELECT O.custid FROM Sales.Orders AS O);
返回0行
原因:
NOT(22=1 Or 22=2 Or 22=NULL)
NOT(False or False Or UnKnown)
NOT UnKnow
Unknow
查询条件过滤UnKnown
而:
SELECT custid, companyname FROM Sales.Customers AS C WHERE not exists (SELECT * FROM Sales.Orders AS O where C.custid=O.custid);
或
SELECT custid, companyname FROM Sales.Customers AS C WHERE custid NOT IN(SELECT O.custid FROM Sales.Orders AS O where O.custid is NOT null);
返回:
custid companyname
22 Customer DTDMN
57 Customer WVAXS