如何加快 sql 查询的执行速度?

How to speed up sql query execution?

任务是执行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) 上的索引(您可以同时尝试两者,看看一个是否比另一个提供更好的改进)。

另一种可能性是使用window函数:

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

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

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

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