简体   繁体   中英

delete distinct data mysql and laravel

hi i have laravel project and i have this model

User_attendance

User

and i have this relation inside User

public function getAttendance()
{
    return $this->hasMany('App\User_attendance','user_attendance_user_id','id');
}

now there is duplication data in User_attendance like this

9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-28 17:35:00
9238<><> 2018-11-29 17:44:34
9238<><> 2018-12-08 17:18:12
9238<><> 2018-12-08 17:18:12

now 9238<><> 2018-11-27 17:45:48 has 12 recored how can i run query inside laravel or mysql to delete 11 recored and leave only 1 i did this

$users = User::limit(30)->get();
foreach($users as $u)
{
    foreach($u->getAttendance as $attendance)
    {
        echo $attendance->user_attendance_user_id . "<><> ".$attendance->created_at ."<br />";
    }
}

i want to delete the duplication data and leave only one recored thanks

Use a double group by something like :

DB::table('users')
            ->select('*')
            ->groupBy('user_attendance_user_id','created_at')
            ->get();

If you want to delete records in the databse, you could do a MySQL query like

DELETE t1 FROM `User_attendance` as f
        INNER JOIN
    `User_attendance` as s 
WHERE
    f.id < s.id AND f.time = s.time AND f.user_attendance_user_id = s.user_attendance_user_id;

This will remove the duplicate entries from your table. You might want to make sure you only insert a new row if it is unique, so do a check in your code (and make the column combination of user id and time unique (ie a UNIQUE index) in the database)

Use the DISTINCT or GROUP BY keyword

Example:

SELECT DISTINCT(column),column1,column2,... FROM table_name;

SELECT * From User_attendance GROUP BY user_attendance_user_id,created_at;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM