sql - 如何加快sql查询执行速度?
问题描述
任务是执行sql查询:
select * from x where user in (select user from x where id = '1')
子查询包含大约 1000 个 id,因此需要很长时间。也许这个问题已经存在,但我怎样才能加快速度呢?(如果可以加快速度,请为 PL SQL 和 T-SQL 或至少其中之一编写)。
解决方案
我将首先将in
条件重写为exists
:
select *
from x
where exists (select 1 from x x1 where x.user = x.user and x1.id = 1)
x(user, id)
然后,考虑一个关于- 或的索引x(id, user)
(您可以同时尝试两者,看看一个是否能提供比另一个更好的改进)。
另一种可能性是使用窗口函数:
select *
from (
select x.*, max(case when id = 1 then 1 else 0 end) over(partition by user) flag
from x
) x
where flag = 1
这可能会或可能不会比not exists
解决方案执行得更好,具体取决于各种因素。
推荐阅读
- python - 将组索引值添加到组
- c++ - 无法正确打印一种图案
- javascript - 尝试使用 javascript 创建自定义 HTML 节点以进行页面注入
- php - 有没有办法在 EasyAdmin 3 中表示 JSON 字段?
- node.js - 托管节点网络爬虫?
- python - Python:如何根据对 CSV 文件的列标题的查找来设置类的变量
- python - 如何将收入值添加到 Python 可视化中每个条形图的顶部?
- r - 如何从 ggplot2 图 R Shiny 中删除白色背景?
- c - 原因 main-C 不是 const
- wpf - 在 Windows 10 上启用拼写检查的 WPF 文本框键入速度缓慢