【问题标题】:delete the duplicate records, and keep the one that have lower id删除重复的记录,保留id较低的记录
【发布时间】:2016-07-19 14:12:57
【问题描述】:

我有

包含错误数据的用户表。我想循环删除email的重复记录,保留lowerid的记录。

我只想保留 id:1、14、1004、1005、1003、1006 和 1007。


我试过了

$users = DB::table('users')->where('id', DB::raw("(select min(`id`) from users)"))->get();

foreach ($users as $user) {
    if ( ???? )) { // <---- I'm not sure what to put here. 
        $user->delete();
    }
}

我注意到了

$users = DB::table('users')-&gt;groupBy('email')-&gt;get();

返回所有我想保留的记录。

【问题讨论】:

  • 抱歉请忽略。我将把它取下来,我正在尝试处理数据。

标签: php laravel laravel-5


【解决方案1】:

试试这样的

// get users with min id
$ids= DB::table('users')->where('id', DB::raw("(select min(`id`) from users)"))->lists('id');

// get all users
$users = \App\User::all();

foreach ($users as $user) {
    if (!in_array($user->id, $ids)) {
        $user->delete();
    }
}

首先列出具有最小 id 的用户的所有 id(具有唯一的电子邮件),然后获取所有用户并遍历它们。删除所有 id 不在其中的用户。

更新

由于上面的查询似乎不起作用,这就是我要尝试的方法(最终不是非常好)

DB::table('users')->select('id', DB::raw('min("id") as lowest_id, email'))->groupBy('email')->lists('id')

【讨论】:

  • 这将只返回一行。你需要group by email
  • @Peter:我得到了同样的结果array:1 [▼ 0 =&gt; 1 ]
  • @Frank : 我们需要使用 group by 吗?
  • $ids= DB::table('users')-&gt;where('id', DB::raw("(select min(id) from users)"))-&gt;groupBy('email')-&gt;lists('id'); 也返回array:1 [▼ 0 =&gt; 1 ]
  • 这对我来说有点难以检查,因为我目前没有任何重复的数据库 - 所以这是我要尝试的:DB::table('users')->select ('id', DB::raw('min("id") aslowest_id, email'))->groupBy('email')->lists('id')
猜你喜欢
  • 2019-12-20
  • 2012-04-12
  • 2015-09-27
  • 2012-07-21
  • 2020-05-14
  • 1970-01-01
  • 2014-10-05
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多