Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何加速sql查询执行?_Sql_Subquery_Query Optimization_Where Clause - Fatal编程技术网

如何加速sql查询执行?

如何加速sql查询执行?,sql,subquery,query-optimization,where-clause,Sql,Subquery,Query Optimization,Where Clause,任务是执行sql查询: select * from x where user in (select user from x where id = '1') 子查询包含大约1000个id,因此需要很长时间。 也许这个问题已经存在了,但我怎样才能加快速度呢?(如果可以加速,请为PL SQL和T-SQL或至少其中一种编写代码)。我将首先将条件中的重写为存在: select * from x where exists (select 1 from x x1 where x.user = x.use

任务是执行sql查询:

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

我将首先将
条件中的
重写为
存在

select * 
from x 
where exists (select 1 from x x1 where x.user = x.user and x1.id = 1)

然后,考虑一个关于<代码> x(用户,ID)<代码> >或>代码> x(ID,用户)< /C> >的索引(您可以同时尝试这两种方法,看看是否有更好的改进)。 另一种可能是使用窗口功能:

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 

这可能比不存在的
解决方案性能更好,也可能没有,这取决于各种因素。

id
通常是唯一的。这样做是否足够

select x.*
from x
where id in ( . . . );
如果
id
还不是表的主键,则需要索引。

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