【问题标题】:How to speed up sql query execution?如何加快sql查询执行速度?
【发布时间】:2020-11-18 23:07:56
【问题描述】:

任务是执行sql查询:

select * from x where user in (select user from x where id = '1')

子查询包含大约 1000 个 id,因此需要很长时间。 也许这个问题已经存在,但我怎样才能加快速度呢? (如果可以加快速度,请为 PL SQL 和 T-SQL 或至少其中之一编写)。

【问题讨论】:

  • “子查询包含大约 1000 个 id”是什么意思?
  • tsql plsql。我删除了这些冲突的标签,请只标记一个数据库:mysql、oracle、postgresql...?

标签: sql subquery query-optimization where-clause


【解决方案1】:

我首先将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 解决方案执行得更好,具体取决于各种因素。

【讨论】:

    【解决方案2】:

    ids 通常是唯一的。这样做就足够了吗?

    select x.*
    from x
    where id in ( . . . );
    

    如果id 还不是表的主键,您可能需要一个索引。

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 2022-01-19
      • 2022-10-05
      • 1970-01-01
      • 2014-05-29
      • 2014-10-04
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多