Friday, April 29, 2011

Finding and displaying duplicates

I have a table. I'd like to search within this table for duplicate titles.
Lets say my data is as follows:

title1, title2, title3, title1, title4, title2, title9

I'd like for my query to search this table and output only the duplicates. So the output would look like:
title1
title1
title2
title2

I know how I can find the duplicates, but it only shows me one of the duplicates and not both.

SELECT id, title, artist_id FROM sm019_songs GROUP BY title HAVING count(title) > 1

Any ideas?

From stackoverflow
  • Here's one way to do it with a subquery. It might make sense to load the subquery into a temp table first. (This would work in SQL server, not sure what the exact MySql syntax would be.)

    select id, title, artist_id
    from sm019_songs
    where title in
    (
        SELECT title
        FROM sm019_songs
        GROUP BY title
        HAVING count(title) > 1
    )
    
  • this is what I came up with in mysql:

    CREATE TEMPORARY TABLE u (title varchar(250))
    TYPE=HEAP;
    INSERT INTO u
    SELECT title FROM t group by title having count(title) > 1;

    SELECT t.title FROM u,t where u.title = t.title

  • I'd just join the table to itself:

    SELECT S1.*, S2.*
    FROM songs S1, songs S2
    WHERE S1.title = S2.title
      AND S1.id != S2.id
    

    -----N

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.