首页 > 解决方案 > 如何加快sql查询执行速度?

问题描述

任务是执行sql查询:

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

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

标签: sqlsubqueryquery-optimizationwhere-clause

解决方案


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


推荐阅读