【问题标题】:Deleting duplicate records from Mysql Table in Laravel7从 Laravel 7 中的 Mysql 表中删除重复记录
【发布时间】:2020-04-20 16:16:41
【问题描述】:

我有一个表名 temp

id,brand,message,created_atupdated_at

随着时间的推移,它开始变得庞大,有 10 万条记录,但其中大部分是现场品牌的重复记录

我写了一个波纹管语句,它适用于少量记录,但对于大量记录,它会卡住。

  $sql="
  delete
  from temp using temp,
  temp e1
  where temp.id > e1.id
  and temp.brand = e1.brand
  and temp.message IS NULL 
  ";
  DB::unprepared($sql);

我想做的是 1.删​​除具有相同品牌名称的重复行,但仅当消息为空时。

【问题讨论】:

  • 您的查询消除了所有没有消息的行,请参阅dbfiddle.uk/…,因此不需要进行自我加入。我还建立了我自己的查询,看看我是否正确理解了你,而没有任何消息。
  • 有什么更新吗?
  • 什么更新我会回答我的答案,但是当你删除所有没有消息的行时,不需要复杂的删除,请参阅链接

标签: mysql laravel-7


【解决方案1】:

我这样做了,它快速且工作正常

$result = DB::table('temp')
      ->select('id','brand')
      ->where('message', NULL)
      ->get();

$ids=array();
        foreach($result->unique('brand') as $brand){
          $ids[]=$brand->id;
        }


if(count($ids)>0){
          foreach(array_chunk($ids, 500) as $chunk) {
            $sql="
            delete
            from temp where id NOT IN ('".implode("','",$chunk)."')";
            DB::unprepared($sql);
          }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2016-01-07
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多