Question: I have three fields in my database: first name, lastname and email. Email is my primary key. I don't have any other fields in my database.

I need to find a mysql query which can delete duplicated primary keys and their values from the database leaving only one unique email in the database.

I use the following command to display all duplicated primary keys. It worked, but I need to delete all other duplicate entries and keep only one. I am using php programming.

```
SELECT *
FROM table_name
WHERE primarykey IN (
SELECT primarykey
FROM table_name
GROUP BY primarykey
HAVING count(primarykey) > 1
)
ORDER BY primarykey

```

Answer: 
Populate a temp table with the ones you want to keep, using GROUP BY, HAVING and MAX on the other columns. Then run your query which deletes too much, then put your copied ones back in. And then make it the actual PK so it doesn't happen again.
Email is *not* your primary key. Primary keys have a constraint on them where duplicates are not allowed. Your problem, by the way, is just an example of why you want to have an auto-incrementing numeric primary key on all tables. It seems too late for that.

One way to solve your problem is using temporary tables. The idea is to copy the data over, and tehn re-insert it:

```
create temporary table tmp_emails as
    select email, firstname, lastname
    from emails
    group by email;

truncate table emails;

insert into emails(email, firstname, lastname)
   select email, firstname, lastname
    from tmp_emails;

```