2

可能重复:
如何使用 SQL 删除重复行?

我有这个查询,它根据相同的名称和年份从表中返回重复的行。

如何删除重复记录,以便表中只有唯一值?

查询是:

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
4

2 回答 2

2

DELETE 语句可以利用子查询来过滤要删除的项目。

通读此

http://www.w3resource.com/sql/delete-statement/delete-with-subqueries.php

于 2012-11-28T18:42:34.287 回答
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)
于 2012-11-28T19:31:38.523 回答