带有子查询的SQL“In”条件

时间:2013-10-30 12:54:03

标签: sql

我想知道执行以下代码的最佳方法是什么:

 select Id,Id2 from someTable
 where Id in (select someId from someTable2)
    or Id2 in (select someId from someTable2)

我检查了执行计划,我可以看到someTable2的两个表扫描(没有索引)。

我正在寻找的解决方案与索引无关,而是与构建此查询的更好方法有关。

提前致谢。

3 个答案:

答案 0 :(得分:2)

SELECT id
     , id2
FROM   sometable
WHERE  EXISTS (
         SELECT someid
         FROM   sometable2
         WHERE  someid IN (sometable.id, sometable.id2)
       )

答案 1 :(得分:1)

使用JOIN

SELECT  DISTINCT a.ID, a.ID2
FROM    someTable a
        INNER JOIN someTable2 b
            ON b.someID IN (a.id, a.id2)

<强>更新

SELECT ID, ID2
FROM someTable a INNER JOIN someTable2 b ON b.someID = a.id
UNION
SELECT ID, ID2
FROM someTable a INNER JOIN someTable2 b ON b.someID = a.id2

答案 2 :(得分:1)

除非someid上有索引,否则任何查询都必须进行完整的表扫描。您可以尝试更改为加入:

 SELECT DISTINCT T1.Id,T1.Id2 
 FROM someTable T1
 LEFT JOIN someTable2 T2 ON T1.Id = T2.someId 
 LEFT JOIN someTable2 T3 ON T1.Id = T3.someId 
 WHERE T2.someId IS NOT NULL 
    OR T3.someId IS NOT NULL