id | name | uid
1 | ekta | 5
2 | ekta | 5
3 | sharma | 10
4 | sharma | 10
希望它像
id | name | uid
1 | ekta | 5
3 | sharma | 10
我正在使用mysql.可能吗?
我不能使用唯一约束查询来创建唯一的输入,因为我希望输入到表中的这些重复条目.
解决方法:
一种方法是使用LEFT JOIN在子查询上连接表.子查询获取每个UID的最低ID.当记录在子查询上没有匹配时,只表示它没有匹配的记录,可以安全删除.
DELETE a
FROM TableName a
LEFT JOIN
(
SELECT uid, MIN(ID) min_ID
FROM TableName
GROUP BY uid
) b ON a.uid = b.uid AND
a.ID = b.min_ID
WHERE b.uid IS NULL
但是,如果UID的记录可以具有不同的名称,则需要在group by子句中包含name,否则将仅保留具有最低ID的唯一uid.
DELETE a
FROM TableName a
LEFT JOIN
(
SELECT uid, MIN(ID) min_ID, name
FROM TableName
GROUP BY uid, name
) b ON a.uid = b.uid AND
a.ID = b.min_ID AND
a.name = b.name
WHERE b.uid IS NULL
标签:sql,mysql,sql-delete,stored-procedures
来源: https://codeday.me/bug/20190901/1780788.html