删除两列连接重复的行

表teh-1400行。


我想删除具有col1和col2重复的行。


例如 - 如果col1是lorem和col2是ipsum

,还有一些下一行 -col1是lorem和col2是应该删除ipsum

该next行。


这是我正在使用的代码,看不出有什么问题,因为最终结果是 - 只剩下一行,所有其他行都被删除。


该表至少有一半关于col1和col2连接的唯一行。


$st = $db->query("select id, col1, col2 from teh");

$st->execute();

$arr = $st->fetchAll();

$check = [];

foreach($arr as $el){

    $str = $el['col1'] . $el['col2'];

    if(in_array($str, $check)){

        $sql = "delete from teh where id = :aid";

        $st = $db->prepare($sql);

        $st->execute([":aid" => $el['id']]);

    }

    else{

        array_push($check, $str);

    }

}


喵喔喔
浏览 202回答 3
3回答

小怪兽爱吃肉

尝试这样的事情:$st = $db->query("select id, col1, col2 from teh");$st->execute();$arr = $st->fetchAll();foreach($arr as $el){&nbsp; &nbsp; $sql = "delete from teh where col1 = acol1 and col2 = acol2 and id <> aid";&nbsp; &nbsp; $st = $db->prepare($sql);&nbsp; &nbsp; $st->execute([":acol1" => $el['col1'], ":acol2" => $el['col2'], ":aid" => $el['id']]);}这个想法是删除与您当时正在检查的行具有相同值但id值不同的所有行。无需以这种方式连接并将其保存到数组中。

森栏

如果你想删除的行具有较高id但同样col1和col2值,你可以简单地DELETE在那里有匹配的行以较低的行存在id价值DELETE&nbsp;t1FROM teh t1JOIN teh t2 ON t2.col1 = t1.col1 AND t2.col2 = t1.col2 AND t2.id < t1.id

喵喵时光机

尝试这样的事情:$st = $db->query("select id, col1, col2 from teh");$st->execute();$arr = $st->fetchAll();foreach($arr as $el){&nbsp; &nbsp; $sql = "delete from teh where col1 = acol1 and col2 = acol2 and id <> aid";&nbsp; &nbsp; $st = $db->prepare($sql);&nbsp; &nbsp; $st->execute([":acol1" => $el['col1'], ":acol2" => $el['col2'], ":aid" => $el['id']]);}这个想法是删除与您当时正在检查的行具有相同值但id值不同的所有行。无需以这种方式连接并将其保存到数组中。
打开App,查看更多内容
随时随地看视频慕课网APP