子查询分两种,有关子查询和无关子查询。
无关子查询很常用:
SELECT TOP 5 * INTO #a FROM [AdventureWorks].[HumanResources].[Employee]
SELECT TOP 8 * INTO #b FROM [AdventureWorks].[HumanResources].[Employee]
SELECT * FROM #a WHERE EmployeeID not in (SELECT EmployeeID FROM #b)
SELECT * FROM #b WHERE EmployeeID not in (SELECT EmployeeID FROM #a)
无关子查询,整个查询过程可以看作是子查询首先返回SQLResult(SQL结果集),然后交给外部查询使用,整个过程子查询只执行一次
而相反,作为相关子查询,子查询的执行的次数依赖于外部查询,外部查询每执行一行,子查询执行一次,比如:
有关 子查询比较重要:
SELECT * FROM #a a
WHERE EXISTS
(
SELECT * FROM #b b WHERE a.EmployeeID=b.EmployeeID
)
-- b 有a没有
SELECT * FROM #b b
WHERE NOT EXISTS
(
SELECT * FROM #a a WHERE a.EmployeeID=b.EmployeeID
)