如何更快地进行子删除查询?

时间:2013-12-08 23:01:53

标签: mysql sql dataset subquery sql-delete

我想问一下有关使mysql子查询更快的问题。这个查询工作正常,但是当我输入该查询时它几乎运行了2.50小时:

delete from callspan where oid not in (select * from (select MIN(oid) from callspan b Group by b.endtime, b.starttime, b.person_oid,b.phonenumber_oid,b.contact,b.description,b.direction,b.duration) x);

如何更快地运行此代码?此外,我尝试用JOIN制作它,但我不这样做.MIT的呼叫数据集中有太多数据,我正在使用该数据集进行培训。你有这些类型的查询的任何解决方案吗?

谢谢,亲切的问候。

1 个答案:

答案 0 :(得分:1)

delete c
  from callspan c
  LEFT
  JOIN 
     ( select MIN(oid) min_oid
         from callspan b 
        Group 
           by b.endtime
            , b.starttime
            , b.person_oid
            , b.phonenumber_oid
            , b.contact
            , b.description
            , b.direction
            , b.duration
      ) x
     ON x.min_oid = c.oid
  WHERE x.min_oid IS NULL;

http://sqlfiddle.com/#!2/dd028/1

或者,您可以反转逻辑 - 创建一个只包含您想要的行的新表,然后删除旧表并使用新数据重新创建它,然后将索引添加回其中 - 它可能更快...

CREATE TABLE new_callspan AS
SELECT x.*
  FROM callspan x 
  JOIN 
     ( SELECT person_oid
            , MIN(oid) min_oid
         FROM callspan
        GROUP
           BY person_oid
     ) y
    ON y.person_oid = x.person_oid
   AND y.min_oid = x.oid;

 DROP TABLE callspan;

 CREATE TABLE callspan AS SELECT * FROM new_callspan;

 DROP TABLE new_callspan;

 ALTER TABLE etc