简体   繁体   English

删除不同的数据mysql和laravel

[英]delete distinct data mysql and laravel

hi i have laravel project and i have this model 嗨,我有laravel项目,我有这个模型

User_attendance

User

and i have this relation inside User 我在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 现在在User_attendance中有重复数据,像这样

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 现在9238<><> 2018-11-27 17:45:48有12记录了如何在laravel或mysql中运行查询以删除11记录并只留下1我做了这个

$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 如果要删除数据库中的记录,则可以执行MySQL查询,例如

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) 您可能要确保仅插入新行(如果它是唯一的),因此请检查代码(并使用户ID和时间的列组合在数据库中唯一)(即UNIQUE索引)

Use the DISTINCT or GROUP BY keyword 使用DISTINCT或GROUP BY关键字

Example: 例:

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

SELECT * From User_attendance GROUP BY user_attendance_user_id,created_at; SELECT *来自User_attendance GROUP BY user_attendance_user_id,created_at;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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