使用IS NULL时左连接有效性

时间:2014-03-09 08:54:54

标签: sql sql-server left-join

我正在使用左连接来检查数据库中是否存储了某些类型的信息。

我想知道如果连接表包含大量与JOIN子句匹配的行,是否会浪费大量资源。

即:

SELECT Applications.*
FROM Applications
LEFT JOIN SomeFeatureRows ON (SomeFeatureRows.ApplicationId = Applications.Id)
WHERE SomeFeatureRows.Id IS NULL;

数据库是否会扫描SomeFeatureRows中的所有行,以查看是否有IdNULL的行?

我只想检查该表中是否有行(具有指定的应用程序ID)。

编辑,可能还包括真正的SQL语句:

SELECT organizations.id AS OrganizationId, 
       organizations.Name, 
       Application.Id as ApplicationId,
       Application.Name as ApplicationName,
       Account.id       AS AccountId, 
       Account.Email, 
       Account.Username ,
       SentEmails. SentAtUtc 
FROM   organizations 
       INNER JOIN applications ON ( organizations.id = applications.organizationid ) 
       LEFT JOIN Incidents ON ( organizations.id = Incidents.organizationid ) 
       LEFT JOIN SentEmails ON ( organizations.id = SentEmails.organizationid AND EmailTypeName = 'IncidentsReminder') 
       CROSS apply (SELECT accounts.id, 
                           accounts.email, 
                           accounts.username 
                    FROM   accounts, 
                           organizationmembers 
                    WHERE  accounts.id = organizationmembers.accountid 
                           AND organizationmembers.organizationid = 
                               organizations.id) 
       Account 
WHERE  Incidents.id IS NULL

1 个答案:

答案 0 :(得分:1)

Here是一篇非常好的文章,解释了使用的不同技术和性能优势:Not ExistsNot InLeft join / Is null

总结:
LEFT JOIN / IS NULL效率较低,因为它不会尝试跳过右表中已匹配的值,返回所有结果并将其过滤掉。使用Not Exists可获得最佳效果,因为它会在执行计划中创建LEFT ANTI SEMI JOIN