首页 > 解决方案 > 大表的查询运行速度很慢

问题描述

有以下2个表:

MainProcessed

Id  Value
---------
1   123
2   234
3   112

MainAdditionalInfo

Id  MainProcessedId Name    Value
--------------------------------------
1   1               'PX'    'px_value'
2   1               'PY'    'py_value'

我需要从表中选择所有在表MainProcessedId中有一些附加信息的数据MainAdditionalInfo(至少一条记录)并且它没有名称为 PX 的记录,或者如果有,这个值应该为 null 或空。

这是我尝试过的,但是由于这些表有很多数据(超过 1 亿条记录,查询运行了很长时间):

select mp.*
from MainProcessed mp (nolock)
left join MainAdditionalInfo mai1 (nolock) on mp.Id = mai1.MainProcessedId
left join MainAdditionalInfo mai2 (nolock) on mp.Id = mai2.MainProcessedId
where
    (mai1.Value is null or mai1.Value = '')
    and (mai1.Name = 'PX' or mai1.Name = null)
    and mai2.name = 'PY'

请注意,名称为 PX 的值可能不存在,也可能存在为 null 或空值,但名称为 PY 的值始终存在。你能建议我改进吗?

此外,我无权查看执行计划或创建新对象(索引)。

标签: sqloptimizationsql-server-2016

解决方案


您可以尝试使用 and 来表达您的exists查询not exists

select p.*
from MainProcessed p
where 
    exists (
        select 1 
        from MainAdditionalInfo a 
        where a.MainProcessedId = p.id)
    and not exists (
        select 1 
        from MainAdditionalInfo a 
        where 
            a.MainProcessedId = p.id 
            and a.Name = 'PX' 
            and a.Value <> ''    -- null values won't pass that test
    ) 

对于此查询的性能,您需要在MainAdditionalInfo(MainProcessedId , Name, Value).


推荐阅读