sql - 大表的查询运行速度很慢
问题描述
有以下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 的值始终存在。你能建议我改进吗?
此外,我无权查看执行计划或创建新对象(索引)。
解决方案
您可以尝试使用 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)
.
推荐阅读
- python - 在 Python 函数中使用 input() 作为参数
- perl - 如何在 File::Find::Rule 的 `or` 替代项中使用 mindepth 和 maxdepth?
- docker - 暂停时的 docker 容器在快照时是否具有与 VM 类似的特性?
- c# - 从 .NET 和 Python 连接 o google 电子表格
- imacros - 如何在 iMacros 中使用数组循环?
- javascript - 为什么隐式 args 调用在显式时不起作用?
- php - docker debian 拉伸图像中缺少 php-redis 存储库
- php - Heroku 降级 PHP 版本
- java - 随机数游戏问题(用户选号,电脑猜)
- vb6 - VB6 ADODC 控件属性连接字符串,在其他PC上不起作用需要用户路径名