1

我有这个查询:

select distinct somecolumn from sometable
          where something = somethingelse and
          someid not in (select anotherid from another tabele where ...);

我认为由于子选择,查询运行速度非常慢。有没有办法重写它,以便可以删除 not in 和 subselect?

4

5 回答 5

3

利用LEFT JOIN

SELECT  someClumn
FROM    sometable a
        LEFT JOIN anotherTable b
            ON a.someID = b.anotherID 
               -- AND condition for anotherTable
WHERE   a.something = somethingelse AND
        b.anotherID IS NULL

为了获得更好的性能,请在列上定义索引:someIDanotherID.

于 2013-02-01T16:13:42.470 回答
3

尝试

select
  distinct somecolumn

from
  sometable t1
  left join anothertable t2 on (t1.someid=t2.otherid and t2.othercondition='else')

where
  t1.something='something else'
  and t2.pk is null
;

并且 t2.otherid 应该被索引。

注意:子查询中的 WHERE 子句位于 JOIN 条件中。

于 2013-02-01T16:14:18.413 回答
3

理论上,NOT EXISTS应该比 优化略好,并且如果是 NULLableNOT IN也应该更可靠(从 SQL Server 的角度来看的详细信息)。虽然我承认我对 MySQL 的了解还不够,无法知道这个查询是否会更好:anotherid

SELECT somecolumn 
  FROM dbo.sometable AS s
  WHERE something = somethingelse 
  AND NOT EXISTS 
  (
    SELECT 1 FROM dbo.[another table]
    WHERE anotherid = s.someid
  );

但我怀疑这里真正的性能问题是缺少索引,而不是子查询的存在。是否被sometable.something索引?怎么样sometable.somied?和[another table].anotherid?也DISTINCT可能需要额外的排序,但它真的有必要吗?如果您有重复项,则可能表明存在设计问题...

于 2013-02-01T16:36:21.757 回答
1
select somecolumn
from sometable
     LEFT JOIN another tabele
        ON someid  = anotherid
          AND (where clause from subquery)
WHERE anotherid IS NULL
    AND something = somethingelse

如果您有一对多的关系,我认为 DISTINCT 是多余的。

于 2013-02-01T16:14:09.770 回答
0

尝试这个

   select  somecolumn from sometable
      where something = somethingelse and
      someid not in (select anotherid from another tabele where ...)
      GROUP BY somecolumn;
于 2013-02-01T16:14:50.120 回答