SQL Query在检索数据时花费了太多时间

时间:2017-07-18 09:58:08

标签: sql sql-server tsql

select 
  * 
from 
  [platformnew].[dbo].[users] u 
where u.Phone not in 
  (select case  
    when convert(varchar(100),phonenumber) <> '' then convert(varchar(100),ISNULL(PhoneNumber,0)) 
    else convert(varchar(100),0)
  end phonenumber 
  from 
     [ecommerce_crm].[dbo].[mpcustomer]
  ) 
and u.Phone not in 
  (select case  
    when convert(varchar(100),phonenumber2) <> '' then convert(varchar(100),ISNULL(PhoneNumber2,0)) 
    else convert(varchar(100),0) 
  end phonenumber2 
  from [ecommerce_crm].[dbo].[mpcustomer]
  ) 
and u.Email not in 
  (select ISNULL(Email,'') 
  from [ecommerce_crm].[dbo].[mpcustomer])
and u.Email not in 
  (select ISNULL(Email2,'') 
  from [ecommerce_crm].[dbo].[mpcustomer])

这个查询需要花费太多时间来执行,我认为需要大约3分钟,请帮我解决一下

3 个答案:

答案 0 :(得分:0)

您需要将Not in更改为不存在,例如

select 
  * 
from 
  [platformnew].[dbo].[users] u 
where u.Phone not exists
  (select  1 from 
     [ecommerce_crm].[dbo].[mpcustomer]
     WHERE   convert(varchar(100),ISNULL([ecommerce_crm].[dbo].[mpcustomer].PhoneNumber,0)) = u.Phone
  ) 

对于转换部分,您只需要isnull convert(varchar(100),ISNULL([ecommerce_crm].[dbo].[mpcustomer].PhoneNumber,0)) 只需删除

时的情况

答案 1 :(得分:0)

当您将所有NOT IN子句更改为NOT EXISTS时,您应该会看到性能提升。 E.g:

and not exists
  (
    select 1
    from [ecommerce_crm].[dbo].[mpcustomer] mpc
    where u.Phone = mpc.Phone
  ) 

此外,所有CONVERT功能都是不必要的。如果phonenumber数据类型为int,则使用此类型编写子句,例如isnull(phonenumber,0)<>0。如果电话号码不应该为空或0,请将其添加为单独的条件,因为现在每次当它为空或0时,您不必要地查找其他表以查找空值而0则丢弃它。

答案 2 :(得分:0)

SELECT * 
FROM [platformnew].[dbo].[users] u
WHERE NOT EXISTS (
    SELECT 1
    FROM [ecommerce_crm].[dbo].[mpcustomer] c
    WHERE c.phonenumber = u.Phone
        OR c.phonenumber2 = u.Phone
        OR c.Email = u.Email 
        OR c.Email2 = u.Email 
    )
    AND u.Phone != '0'
    AND u.Email != ''