MYSQL PHP基于重复列将多行合并为一行


MYSQL PHP Combine Multiple Rows into One Based on a Duplicate Column

我有一个电子邮件列表,其中有很多重复的数据,我想合并某些列中有重复数据的行。

这是我的表格:

autoid,title,lastname,firstname,middlename,prefix,
fulladdress,address1,address2,
city,state,zip,country,county,phone1,phone2,email,id, ts

我想根据email和phone1合并重复的行。如果这两行中的内容是相同的,那么我想要合并这两行,然后填上空白,然后去掉第二行。autoid值较低的行中的数据将优先于id值较高的行。

如果我们能做到这一点与一个单一的mysql查询将是伟大的,但如果我们必须使用PHP,也将工作。

您可以使用类似

这样的命令将多行合并为单个行
GROUP BY email, phone1

如果你插入这个,你会得到任意一个组合行。如果您希望值优先于NULL字段,您可以使用聚合函数,例如MIN:

SELECT MIN(title), MIN(lastname), …
FROM tableName
GROUP BY email, phone1

但是这会决定为每一行分别取哪个值。以您描述的方式合并行的查询在MySQL中是相当棘手的。您可以有一个查询,列出所有行的匹配列的顺序,然后降序autoid,使用用户变量来填补空白。但是,不填补不匹配行的空白会很困难,因此为每个匹配对设置一个子查询可能会更好。除了性能和查询的可读性之外,总的来说,您最好使用PHP解决方案。

在PHP中,事情应该相当简单:使用

查询数据库
ORDER BY email, phnone1, autoid ASC

,然后在PHP端,对于从数据库中读取的每一行,检查它是否与之前在两个特定列中读取的行匹配。如果是,遍历列,替换null s。我现在不是一个PHP程序员,所以其他人可能更适合为这个编写代码片段。

我们真的不喜欢在StackOverflow上提供完整的代码解决方案,通常我们会帮助您编写自己的代码,但我不确定我是否可以在没有实际编写代码的情况下解释所有步骤,所以这里是一些入门代码。

这是未经测试的原始代码

首先复制你现有的表,直到我们知道这段代码不会损害或丢失你现有的数据,在一个副本上做所有的事情,然后一旦它被熨平,你已经验证它将正常工作,然后应用到正确的表

使用:

创建副本
CREATE TABLE EmailListCopy LIKE EmailList; 
INSERT EmailListCopy SELECT * FROM EmailList;
PHP代码:

<?php
//This script will first query the table for ALL results, store them in arrays, 
//then loop through the arrays to search the table for duplicates using individual
//sql queries and then compare the results, update the entry as needed and delete the
//duplicate row. THIS CODE IS NOT OPTIMIZED!! DO NOT RUN CONTINUOUSLY!! This should be
//used for OCCASIONAL merging ONLY!! i.e. Once-a-day or once-a-week etc...
$result="";
$duplicatesFound;
//Setup arrays to hold the original query information
$autoidArray = array();
$titleArray = array();
$lastnameArray = array();
$firstnameArray = array();
$middlenameArray = array();
$prefixArray = array();
$fulladdressArray = array();
$address1Array = array();
$address2Array = array();
$cityArray = array();
$stateArray = array();
$zipArray = array();
$countryArray = array();
$countyArray = array();
$phone1Array = array();
$phone2Array = array();
$emailArray = array();
$idArray = array();
$tsArray = array();
$link=mysqli_connect($hostname,$dbname,$password,$username);
if(mysqli_connect_errno())
{
    $result="Error connecting to database: ".mysqli_connect_error();
}
else
{
    $stmt=mysqli_prepare($link,"SELECT autoid,title,lastname,firstname,middlename,prefix,fulladdress,address1,address2,city,state,zip,country,county,phone1,phone2,email,id,ts FROM " . $table);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $autoid, $title, $lastname, $firstname, $middlename, $prefix, $fulladdress, $address1, $address2, $city, $state, $zip, $country, $county, $phone1, $phone2, $email, $id, $ts);
    if(mysqli_stmt_errno($stmt))
    {
        $result="Error executing SQL statement: ".mysqli_stmt_error($stmt);
    }
    else
    {
        mysqli_stmt_store_result($stmt);
        if(mysqli_stmt_num_rows($stmt)==0)
        {
            $result="0 rows returned (Empty table)";
        }
        else 
        {
            while(mysqli_stmt_fetch($stmt))
            {
                //Load results into arrays
                array_push($autoidArray, $autoid);
                array_push($titleArray, $title);
                array_push($lastnameArray, $lastname);
                array_push($firstnameArray, $firstname);
                array_push($middlenameArray, $middlename);
                array_push($prefixArray, $prefix);
                array_push($fulladdressArray, $fulladdress);
                array_push($address1Array, $address1);
                array_push($address2Array, $address2);
                array_push($cityArray, $city);
                array_push($stateArray, $state);
                array_push($zipArray, $zip);
                array_push($countryArray, $country);
                array_push($countyArray, $county);
                array_push($phone1Array, $phone1);
                array_push($phone2Array, $phone2);
                array_push($emailArray, $email);
                array_push($idArray, $id);
                array_push($tsArray, $ts);
            }
        }
        mysqli_stmt_free_result($stmt);
    }
    for($i=0;$i<count($emailArray);$i++)
    {
        $duplicatestmt=mysqli_prepare($link,"SELECT autoid,title,lastname,firstname,middlename,prefix,fulladdress,address1,address2,city,state,zip,country,county,phone1,phone2,email,id,ts FROM " . $table . " WHERE email=? OR phone1=?");
        mysqli_stmt_bind_param($duplicatestmt, 'si', $emailArray[$i], $phone1Array[$i]);
        mysqli_stmt_execute($duplicatestmt);
        mysqli_stmt_bind_result($duplicatestmt, $autoid, $title, $lastname, $firstname, $middlename, $prefix, $fulladdress, $address1, $address2, $city, $state, $zip, $country, $county, $phone1, $phone2, $email, $id, $ts);
        if(mysqli_stmt_errno($duplicatestmt))
        {
            $result="Error executing SQL statement: ".mysqli_stmt_error($duplicatestmt);
        }
        else
        {
            mysqli_stmt_store_result($duplicatestmt);
            if(mysqli_stmt_num_rows($duplicatestmt)==0)
            {
                //NO Duplicate entry found, loop again;
                echo "<p>No Dublicate Found</p>";
            }
            else 
            {
                while(mysqli_stmt_fetch($duplicatestmt))
                {
                    //Found a duplicate
                    echo "<p>Dublicate Found</p>";
                    if($autoid > $autoidArray[$i])
                    {
                        if($email=="" && $phone1=="")
                        {
                            echo "<p>Both email and phone1 are empty. Skipping...</p>";
                        else
                        {
                        $duplicatesFound++;
                        //The autoid of the duplicate just found is greater then the autoid of the
                        //one used to find the duplicate (older). Therefor update the entry and remove the
                        //duplicate
                        //
                        //This checks each of the values and if the lower autoid one is blank, then will add the
                        //value to the table in the lower autoid row
                        //NOTE:** If having any problems with the queries below try removing the single quotes -> ' <- from any "autoid=" portion of the query
                        if($titleArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$title."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($lastnameArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$firstname."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($firstnameArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$lastname."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($middlenameArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$middlename."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($prefixArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$prefix."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($fulladdressArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$fulladdress."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($address1Array[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$address1."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($address2Array[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$address2."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($cityArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$city."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($stateArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$state."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($zipArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$zip."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($countryArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$country."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($countyArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$county."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($phone1Array[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$phone1."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($phone2Array[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$phone2."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($emailArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$email."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($idArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$id."' WHERE autoid='".$autoidArray[$i]."'");}
                        if($tsArray[$i]==""){mysqli_query($link,"UPDATE EmailListCopy SET title='".$ts."' WHERE autoid='".$autoidArray[$i]."'");}
                        //Now that it has been updated, delete the duplicate entry
                        mysqli_query($link, "DELETE FROM EmailListCopy WHERE autoid='".$autoid."'");
                        echo "<p>Duplicate to be updated DELETE FROM EmailListCopy WHERE autoid='".$autoid."'</p>";
                        }
                    }
                    else
                    {
                        //The duplicate autoid is lower then the one used to query either an entry we already but is still in the arrays, or something else. 
                        //This is to be skipped.
                        echo "<p>Duplicate not to be updated</p>";
                    }
                }
                $result="Merged ".$duplicatesFound." rows.";
            }
            mysqli_stmt_free_result($stmt);
        }
    }
    mysqli_stmt_close($duplicatestmt);
    mysqli_stmt_close($stmt);
    mysqli_close($link);
}
echo $result;
?>