删除重复数据
使用DISTINCT关键字和UNION操作符
SELECT DISTINCT * FROM (
SELECT column_name1, column_name2, ... FROM table_name
UNION
SELECT column_name1, column_name2, ... FROM table_name
) AS tmp;
这个方法会将表中的所有行复制到临时表中,并使用DISTINCT关键字删除重复的行。
使用GROUP BY和HAVING子句
DELETE table_name
FROM table_name
WHERE column_name IN (
SELECT column_name
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1
);
这个方法将使用子查询查找具有重复值的列,并在主表中删除这些行。
使用NOT IN或LEFT JOIN
DELETE table_name
FROM table_name
WHERE id NOT IN (
SELECT MIN(id)
FROM table_name
GROUP BY column_name
);
或者使用左连接
DELETE t1
FROM table_name t1
LEFT JOIN (
SELECT MIN(id) AS id
FROM table_name
GROUP BY column_name
) t2 ON t1.id = t2.id
WHERE t2.id IS NULL;
这两种方法都会从表中删除重复值,但不会删除包含重复值的列中的所有行。而是只删除重复值中的一行。