当我得到不同的记录计数时,出现了这个问题,我认为是使用not in where约束的相同查询,另一个是a left join.not in约束中的表有一个空值(坏数据),导致该查询返回0个记录的计数.我有点理解为什么,但我可以使用一些帮助来完全理解这个概念.
简单地说,为什么查询A返回结果但B不返回?
A: select 'true' where 3 in (1, 2, 3, null)
B: select 'true' where 3 not in (1, 2, null)
Run Code Online (Sandbox Code Playgroud)
这是在SQL Server 2005上.我还发现调用set ansi_nulls off导致B返回结果.
我目前正在通过Microsoft SQL Server 2008 - 数据库开发(MCTS考试70-433)认证.在前面有关组合数据集的章节中,我遇到了EXCEPT(和INTERSECT)命令.一个示例显示如何使用EXCEPT从第一个表中没有相关值的表中获取所有值,如下所示:
SELECT EmployeeKey FROM DimEmployee
EXCEPT
SELECT EmployeeKey FROM FactResellerSales
Run Code Online (Sandbox Code Playgroud)
这个EXCEPT命令对我来说是新的,但是根据我今天所知道的,我仍然可以使用a轻松地解决问题,LEFT JOIN并IS NULL通过以下方式检查连接约束:
SELECT DISTINCT DimEmployee.EmployeeKey FROM DimEmployee
LEFT JOIN FactResellerSales ON FactResellerSales.EmployeeKey = DimEmployee.EmployeeKey
WHERE FactResellerSales.EmployeeKey IS NULL
Run Code Online (Sandbox Code Playgroud)
现在我开始怀疑其中哪一个具有最佳性能.我试图研究查询执行计划,但我不太擅长阅读这些,所以它并没有让我更聪明.对于使用的查询EXCEPT,计划如下所示:
|--Nested Loops(Left Anti Semi Join, OUTER REFERENCES:([AdventureWorksDW2008].[dbo].[DimEmployee].[EmployeeKey], [Expr1006]) WITH UNORDERED PREFETCH)
|--Index Scan(OBJECT:([AdventureWorksDW2008].[dbo].[DimEmployee].[IX_DimEmployee_SalesTerritoryKey]))
|--Top(TOP EXPRESSION:((1)))
|--Index Seek(OBJECT:([AdventureWorksDW2008].[dbo].[FactResellerSales].[IX_FactResellerSales_EmployeeKey]), SEEK:([AdventureWorksDW2008].[dbo].[FactResellerSales].[EmployeeKey]=[AdventureWorksDW2008].[dbo].[DimEmployee].[EmployeeKey]) ORDERED FORWARD)
Run Code Online (Sandbox Code Playgroud)
对于使用LEFT JOIN它的人看起来像这样:
|--Stream Aggregate(GROUP BY:([AdventureWorksDW2008].[dbo].[DimEmployee].[EmployeeKey])) …Run Code Online (Sandbox Code Playgroud) sql-server sqlperformance sql-server-2008 sql-execution-plan
我想写一个sql查询,并希望从DEPT表中获取没有在EMP表中分配员工的dept名称.
表结构:
EMP
EMPNO ENAME DEPTNO
DEPT
DEPTNO DNAME
Run Code Online (Sandbox Code Playgroud)
所以我想知道那些没有员工协会的DEPT.