PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 6, 2022

[FIXED] delete the duplicate records, and keep the one that have lower id

 February 06, 2022     laravel, laravel-5, php     No comments   

Issue

I have

a users table that contains bad data. I want to loop through and delete the duplicate records in term of email, and keep the record that have lower id.

enter image description here

I want to keep only id : 1, 14, 1004, 1005, 1003, 1006, and 1007.


I've tried

$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();
    }
}

I noticed

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

return all the records I want to keep.


Solution

Try something like this

// 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();
    }
}

First List all ids of the users with the minimum id ( with unique email ) , then get all users and loop through them. Delete every user who's id is not in it.

UPDATE

Since the upper query seems not to work here's what I would try ( not finally veryfied )

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


Answered By - Frnak
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing