我有这个查询,它以相同的名称和年份从表中返回重复的行。
如何删除重复记录,因此表中只有唯一值?
查询是:
SELECT movies.movie_name, movies.year
FROM movies
INNER JOIN
(
SELECT movie_name, year
FROM movies
GROUP BY movie_name,year
HAVING count(movie_id) > 1
) dup
ON movies.movie_name = dup.movie_name
and movies.year = dup.year
答案 0 :(得分:2)
DELETE语句可以使用子查询来过滤要删除的项目。
通读本
http://www.w3resource.com/sql/delete-statement/delete-with-subqueries.php
答案 1 :(得分:2)
此查询显示所有重复项:
SELECT movie_name, year
FROM movies
GROUP BY movie_name,year
HAVING count(movie_id) > 1
这只显示每部电影的movie_id(重复或不重复),这些是要保留的行:
SELECT movie_name, year, min(movie_id) min_movie_id
FROM movies
GROUP BY movie_name,year
要删除重复项,您可以使用:
DELETE movies
FROM
movies inner join
(SELECT movie_name, year, min(movie_id) min_movie_id
FROM movies
GROUP BY movie_name,year) keep
on movies.movie_name = keep.movie_name
and movies.year=keep.year
and movies.movie_id<>keep.min_movie_id
或者您也可以使用此查询:
delete from movies
where
(movie_name, year, movie_id) not in
(select movie_name, year, min_movie_id from
(SELECT movie_name, year, min(movie_id) min_movie_id
FROM movies
GROUP BY movie_name,year) keep)