我有一个用户列表(Field = UserName),我从表(用户)获得。有些是重复的。
如果有重复记录,我需要删除创建的最新记录(CreatedOn)。
此外,如果因为与此用户ID建立了关系,它会因删除功能而崛起。在数据库中,我需要它跳到下一条记录并继续删除。
我该如何做到这一点?
答案 0 :(得分:1)
从Diego的答案中添加,检查UserName不是表中最旧的实例。
DELETE FROM
Users
WHERE
UserName IN
(SELECT UserName FROM Users GROUP BY UserName HAVING COUNT(UserName) > 1)
AND
CreatedOn !=
(SELECT MIN(CreatedOn) FROM Users T1 WHERE UserName = T1.UserName);
答案 1 :(得分:0)
您可以尝试这样的事情:
Delete from Users
where nameuser in
(select nameuser from Users
Group by nameuser
Having count(nameuser) > 1)
答案 2 :(得分:0)
如果同一UserName也有较旧的CreatedOn,请使用git checkout differentBranch
git cherry-pick <commit # from previous commit from your first branch>
删除行:
EXISTS
或者,另一种方法:
delete from users u1
where exists (select 1 from users u2
where u2.UserName = u1.UserName
and u2.CreatedOn < u1.CreatedOn)
答案 3 :(得分:0)
DELETE from user u
WHERE u.UserId in ( SELECT Distinct userid from User u join User u2 where u.UserName = u2.UserName
and u.CreatedOn > u2.CreatedOn)
您不能在一个sql中跳过错误,但可以排除相关表中存在的用户ID。