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.
Could you try this?

```
DELETE t1 FROM test t1, test t2
WHERE t1.email  = t2.email
    AND t1.fn > t2.fn
    AND t1.ln > t2.ln;

```

Here are tests:

```
CREATE TABLE test
(
    email varchar(100),
    fn varchar(100),
    ln varchar(100)
);

INSERT INTO test VALUES('a@b', 'f1', 'l1');
INSERT INTO test VALUES('a@b', 'f2', 'l2');
INSERT INTO test VALUES('c@d', 'f2', 'l2');

mysql> SELECT * FROM test;
+-------+------+------+
| email | fn   | ln   |
+-------+------+------+
| a@b   | f1   | l1   |
| a@b   | f2   | l2   |
| c@d   | f2   | l2   |
+-------+------+------+
3 rows in set (0.00 sec)

mysql>     DELETE t1 FROM test t1, test t2
    ->     WHERE t1.email  = t2.email
    ->         AND t1.fn > t2.fn
    ->         AND t1.ln > t2.ln;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM test;
+-------+------+------+
| email | fn   | ln   |
+-------+------+------+
| a@b   | f1   | l1   |
| c@d   | f2   | l2   |
+-------+------+------+
2 rows in set (0.00 sec)

```