PHP代码删除除MySQL数据库表中的一条记录之外的所有重复记录

PHP code to delete all duplicate records except One in MySQL database table

提问人:Xpert Solutions 提问时间:11/27/2022 更新时间:11/27/2022 访问量:57

问:

我有一个数据库表,记录了超过 300,000 家公司。

每条记录都有电话号码。 我只想从重复的记录中保留一条记录。

例如:

编号 标题 电话
1 公司 01 111 111 11
2 公司 02 222 222 22
3 公司 03 333 333 33
4 公司 04 444 444 44
5 公司 05 333 333 33
6 公司 06 555 555 55
7 公司 07 222 222 22
8 公司 08 333 333 33
9 公司 09 666 666 66

我想保留 id (2, 7) 中的任意一条记录和 id (3, 5, 8) 中的一条记录

我可以通过 GROUP BY 查询找到重复的记录,但不确定如何删除。

这就是我正在做的

<?php
$qry    = "SELECT phone, COUNT(*) as total FROM companies GROUP BY phone HAVING COUNT(*) > 1"
$result = mysqli_query($dbConn, $qry);
while($row = mysqli_fetch_array($result)) 
{
    // here should be code to keep one record
    
    // here is code to delete duplicate records
    $qry_del    = "DELETE from companies where phone = '".$row['phone']."'";
    mysqli_query($dbConn, $qry_del);
}
?>
PHP 数据库 mysqli

评论

0赞 Simon Goater 11/27/2022
你可以把像 SELECT MIN(id) AS minid, phone...etc,然后将 AND id > $row['minid'] 添加到 DELETE 查询中。如果未对电话列编制索引,则此方法可能效率非常低下。
0赞 Simon Goater 11/27/2022
...当然,假设 ID 是唯一的。
1赞 symcbean 11/27/2022
您的示例“重复项”具有不同的公司值。你没有说你的删除/保留标准是什么。

答:

-2赞 user141080 11/27/2022 #1

如果性能和持续时间不是那么重要,您可以按电话号码选择公司,然后按标识符删除它们。

也许以下脚本会对您有所帮助:

$qry    = "SELECT phone, COUNT(*) as total FROM companies GROUP BY phone HAVING COUNT(*) > 1";

$result = mysqli_query($dbConn, $qry);

while($row = mysqli_fetch_array($result))
{
    // temporary storage for the companies IDs which should deleted
    $recordsToDelete = [];

    // counter that controls how many records are to be deleted
    $maxCountToDelete = $row['total'] - 1;

    // get all companies with specific phone number
    $selectCompanies    = "SELECT id FROM companies WHERE phone = '". $dbConn->real_escape_string( $row['phone'] ) ."'";
    $resultCompanies = mysqli_query($dbConn, $selectCompanies);

    // collect the ids
    $i= 0;
    while($rowCompanie = mysqli_fetch_array($resultCompanies ))
    {
        if( $i < $maxCountToDelete){
            $recordsToDelete[] = $rowCompanie['id'];
        }

        $i++;
    }

    // delete the companies in one SQL statment
    $qryDel    = "DELETE FROM companies WHERE id IN  (". $dbConn->real_escape_string( implode(',', $recordsToDelete) ) .") ";
    

    mysqli_query($dbConn, $qryDel );
}

请注意,“maxCountToDelete”之所以有效,是因为您的删除条件是您希望通过手机选择公司,而不管公司名称是否不同

评论

0赞 Simon Goater 11/28/2022
不需要两个 SELECT。
0赞 user141080 11/28/2022
你是绝对正确的,但也许我的解决方案对于一个没有那么有经验的开发人员来说更容易理解。这就是我发布它的原因。