执行 20 万行 SQL 查询需要一个多小时

标签 sql sql-server performance ssms

我有两个表,每个表约有 200,000 行。我已经运行了下面的查询,但运行了一个多小时后仍然没有完成。对此有何解释?

SELECT 
    dbo.[new].[colom1],
    dbo.[new].[colom2],
    dbo.[new].[colom3],
    dbo.[new].[colom4],  
    dbo.[new].[Value] as 'nieuwe Value',
    dbo.[old].[Value] as 'oude Value'
FROM dbo.[new]
JOIN dbo.[old] 
    ON dbo.[new].[colom1] = dbo.[old].[colom1] 
    and dbo.[new].[colom2] = dbo.[old].[colom2] 
    and dbo.[new].[colom3] = dbo.[old].[colom3] 
    and dbo.[new].[colom4] = dbo.[old].[colom4] 
where dbo.[new].[Value] <> dbo.[old].[Value]

来自评论;

Execution plan

Table structure

最佳答案

看起来,对于单列上的等式连接,连接键中具有 NULL 值的行将被过滤掉,但对于多列上的连接,情况并非如此
结果,哈希连接复杂度从 O(N) 变为 O(N^2)。

================================================== =======================

在这种情况下,我想推荐 Paul White 就类似问题撰写的一篇精彩文章 - Hash Joins on Nullable Columns

================================================== =======================

我已经生成了这个用例的一个小型模拟,我鼓励您测试您的解决方案。

create table mytab1 (c1 int null,c2 int null)
create table mytab2 (c1 int null,c2 int null)

;with t(n) as (select 1 union all select n+1 from t where n < 10)
insert into mytab1 select null,null from t t0,t t1,t t2,t t3,t t4

insert into mytab2 select null,null from mytab1

insert into mytab1 values (111,222);
insert into mytab2 values (111,222);
<小时/>
select * from mytab1 t1 join mytab2 t2 on t1.c1 = t2.c1 and t1.c2 = t2.c2 
<小时/>

对于 OP 查询,我们应该删除任何连接键列中具有 NULL 值的行。

SELECT 
    dbo.[new].[colom1],
    dbo.[new].[colom2],
    dbo.[new].[colom3],
    dbo.[new].[colom4],  
    dbo.[new].[Value] as 'nieuwe Value',
    dbo.[old].[Value] as 'oude Value'
FROM dbo.[new]
JOIN dbo.[old] 
    ON dbo.[new].[colom1] = dbo.[old].[colom1] 
    and dbo.[new].[colom2] = dbo.[old].[colom2] 
    and dbo.[new].[colom3] = dbo.[old].[colom3] 
    and dbo.[new].[colom4] = dbo.[old].[colom4] 
where dbo.[new].[Value] <> dbo.[old].[Value]
    and dbo.[new].[colom1]  is not null
    and dbo.[new].[colom2]  is not null
    and dbo.[new].[colom3]  is not null
    and dbo.[new].[colom4]  is not null
    and dbo.[old].[colom1]  is not null
    and dbo.[old].[colom2]  is not null
    and dbo.[old].[colom3]  is not null
    and dbo.[old].[colom4]  is not null

关于执行 20 万行 SQL 查询需要一个多小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41302138/

相关文章:

MySQL连接三个表

c# - 无法使用脚本任务将更新的值分配给 ssis 变量

sql-server - 提交事务需要太长时间?

c# - 存储过程读取xml,有什么更好的办法吗? SQL 服务器 2008

c# - 将文件内容导入数据库的最快且最佳的方法

php - 插入查询后,来自表单的数据在数据库中显示为乱码

mysql - 高效的 CASE 语句,SQL

performance - Fortran的表现

c - 结构效率

c++ - 为什么代码以线性方式比以循环方式运行得慢?