为了账号安全,请及时绑定邮箱和手机立即绑定

删除两列连接重复的行

删除两列连接重复的行

PHP
喵喔喔 2021-11-19 16:12:56
表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);    }}
查看完整描述

3 回答

?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

尝试这样的事情:


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

$st->execute();

$arr = $st->fetchAll();

foreach($arr as $el){

    $sql = "delete from teh where col1 = acol1 and col2 = acol2 and id <> aid";

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

    $st->execute([":acol1" => $el['col1'], ":acol2" => $el['col2'], ":aid" => $el['id']]);

}

这个想法是删除与您当时正在检查的行具有相同值但id值不同的所有行。无需以这种方式连接并将其保存到数组中。


查看完整回答
反对 回复 2021-11-19
?
森栏

TA贡献1810条经验 获得超5个赞

如果你想删除的行具有较高id但同样col1和col2值,你可以简单地DELETE在那里有匹配的行以较低的行存在id价值


DELETE 

t1

FROM teh t1

JOIN teh t2 ON t2.col1 = t1.col1 AND t2.col2 = t1.col2 AND t2.id < t1.id


查看完整回答
反对 回复 2021-11-19
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

尝试这样的事情:


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

$st->execute();

$arr = $st->fetchAll();

foreach($arr as $el){

    $sql = "delete from teh where col1 = acol1 and col2 = acol2 and id <> aid";

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

    $st->execute([":acol1" => $el['col1'], ":acol2" => $el['col2'], ":aid" => $el['id']]);

}

这个想法是删除与您当时正在检查的行具有相同值但id值不同的所有行。无需以这种方式连接并将其保存到数组中。


查看完整回答
反对 回复 2021-11-19
  • 3 回答
  • 0 关注
  • 197 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信