0

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

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

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

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

提前致谢。

4

3 回答 3

2
SELECT id
     , id2
FROM   sometable
WHERE  EXISTS (
         SELECT someid
         FROM   sometable2
         WHERE  someid IN (sometable.id, sometable.id2)
       )
于 2013-10-30T13:01:06.990 回答
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
于 2013-10-30T12:55:34.687 回答
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
于 2013-10-30T12:57:49.643 回答