1

注意:致编辑:如果有更好的标题,请编辑标题:)

我的问题是:

我的数据库中有两个表

     -----------
     | table1   |
     |----------|
     | id       |
     |text      |
     ===========


     -----------
     | table2   |
     |----------|
     | id       |
     |text      |
     ===========

table1 是 600,000 条记录

table2 是 5,000,000 条记录!!:)

删除table2中所有不在table1中的记录的最佳方法是什么

顺便说一句-最快的方法,因为我不想等待 4 小时才能完成该过程

你有比下面的代码更好的东西吗:

<?PHP
   $sql = "select text from table2";
   $result = mysql_query($sql) or die(mysql_error());
   while($row = mysql_fetch_array($result)){
        $text = $row["text"];
        $sql2 = "select id from table1 where text = '$text'";
        $query2 = mysql_query($sql2) or die(mysql_error());
        $result2 = mysql_num_rows($query2);
        if($result2==0){
             $sql3 = "delete from table2 where text = '$text'";
             $query3 = mysql_query($sql3) or die(mysql_error());
        }
   }
?>

谢谢

4

5 回答 5

5

让 RDBM 处理它怎么样?

例如

DELETE FROM table2 WHERE text NOT IN (select distinct text from table1)

干杯

PS:测试前做一些备份...

于 2009-09-17T04:51:39.447 回答
3

您的解决方案是在 table2 表中每行执行 2 个查询 - 这意味着数百万个查询 - 这将相当慢^^

使用 MySQL,您可能只需一个查询即可删除所有这些:该DELETE指令可用于从多个表中删除数据。

首先是编写将匹配您要删除的数据的选择指令(这是一种更好的测试方法,而不是在不知道它是否真的会处理正确的数据的情况下尝试删除);这样的事情可能会做:

select table2.*
from table2
    left join table1 on table1.text = table2.text
where table1.id is NULL

这应该会为您提供 table2 中但不在 table1 中的所有数据。

一旦您确定此查询获取正确的数据,您可以将其转换为删除查询:

delete table2
from table2
    left join table1 on table1.text = table2.text
where table1.id is NULL

这可能会 - 当然,最好先在测试数据库上进行测试,而不是在您的生产数据库上进行测试!

否则,带有 IN 和子查询的东西可能会做;有一点像

delete
from table2
where text not in (select text from table1)

但是,考虑到您拥有的数据量,不确定什么会更快——无论哪种方式,我都不会执行您建议的那种 PHP 循环,但会使用可以自行删除所有内容的 SQL 查询:避免所有从 PHP 到 DB 的那些调用肯定会让事情变得更快!

于 2009-09-17T04:53:25.993 回答
1

为什么不向 table2 添加一个一个字节的新列,然后只需将该字节更新设置为 true 或“Y”,如果该行在两个表中。

然后,只需删除没有设置这一列的行。

这似乎是最简单和最快的,IMO。

于 2009-09-17T04:52:15.093 回答
1

尝试这个:

DELETE table2 Where id NOT IN (SELECT id from table1)

注意:在运行查询之前进行备份

于 2009-09-17T05:04:05.177 回答
0

创建 table3 像 table2 插入 table3 (SELECT table2.ID, TABle2.TEXT from table1 join table2 on ...) drop table2 alter table3 new name table2

涉及一些管理(因此,如果您可以轻松删除/更改表,这只是一个有效的选项),但至少 DML 部分将胜过任何其他选项,我认为。

于 2009-09-17T10:24:18.823 回答