如何解决 IN 子句 SQL 查询大量数据中的性能问题?

how to resolve preformance issue in IN Clause SQL Query for huge set of data?

我正在尝试从庞大的数据集中进行查询。查询保持 运行ning 没有任何结果也没有错误。我 运行 对一小组测试数据的相同查询工作正常。

查询:

> SELECT * FROM table1 t1 WHERE t1.col1 IN (SELECT distinct(t2.col2)
> FROM table2 t2 Left Join table3 t3 on t2.col1 = t3.col1  WHERE
> t3.col1=value);

我再次尝试使用

查询大量数据

SELECT * FROM table1 t1 WHERE t1.col1 = (raw_value); - 单值过滤器工作正常。

SELECT * FROM table1 t1 WHERE t1.col1 IN ( raw_value, raw_value); - 多于一个值的过滤器会导致性能问题。

请给我改进性能的建议。

-谢谢。

据我所知,不需要子查询中的 left join,因为过滤器位于用于 on 条件的同一列上:如果是这样,只需将其删除。我建议用 exists:

来表达查询
select t1.*
from table1 t1
where exists (select 1 from table2 t2 on t2.col2 = t1.col1 and t2.col1 = value)

为了性能,您需要 table2(col1, value) 上的索引。 table1(col1) 上的索引也可能有帮助。

大型 IN() 子句的性能总是很差 - 没有办法解决这个问题。解决方案是使用 JOIN 而不是 IN()。

更快的是:

SELECT    *
FROM      table1 t1
JOIN      table2 t2 ON t1.col1 = t2.col2
LEFT JOIN table3 t3 ON t2.col1 = t3.col1
WHERE     t2.col1=value;

此外,这里的LEFT JOIN实际上不会做任何事情,所以最佳形式是:

SELECT    *
FROM      table1 t1
JOIN      table2 t2 ON t1.col1 = t2.col2
WHERE     t2.col1=value;

确保你有索引

table2 (col1)
table2 (col2)