我有一个表“ table1”,其中包含近40万条记录。还有另一个表“ table2”,它具有大约450,000条记录。
我需要删除表1中所有在表2中重复的行。我一直在尝试使用php来执行脚本,该脚本已运行了几个小时,但尚未完成。真的需要那么多时间吗?
字段asin是table1中的varchar(20)
ASIN字段是Table2中的Index和char(10)
$duplicat = 0;
$sql="SELECT asin from asins";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$ASIN = $row['asin'];
$sql2 = "select id from asins_chukh where ASIN='$ASIN' limit 1";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
$duplicat++;
$sql3 = "UPDATE `asins` SET `duplicate` = '1' WHERE `asins`.`asin` = '$ASIN';";
$result3 = $conn->query($sql3);
if($result3) {
echo "duplicate = $ASIN <br/>";
}
}
}
}
echo "totaal :$duplicat";
您可以运行一个单独的sql命令,而不是运行循环,例如:
update table_2 t2
set t2.duplicate = 1
where exists (
select id
from table_1 t1
where t1.id = t2.id);
警告!我没有测试上面的sql,因此您可能需要验证语法。
对于这种数据库操作,使用php循环和联接从来都不是一个好主意。大多数时间将浪费在php服务器和mysql服务器之间的网络数据传输上。
如果以上sql花费的时间太长,则可以考虑将查询集限制在一定范围内。就像是:
update table_2 t2
set t2.duplicate = 1
where exists (
select id
from table_1 t1
where t1.id = t2.id
and t2.id > [range_start] and t2.id < [range_end] );
这样,您可以启动并行运行的多个更新
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句