0

I have a table with customer info. Normally, the PHP checks for duplicates before they new rows are inserted. However, I had to dump a lot of older rows manually and now that they are all in my table, I need to check for duplicates.

Example rows:

id, name, email, phone, fax

I would like to do a mysql query that will show all ID's with matching emails. I can modify the query later for phone, fax, etc.

I have a feeling I will be using DISTINCT, but I am not quite sure how it's done.

1 Answer 1

2

You can GROUP BY email with HAVING COUNT(*) > 1 to find all duplicate email addresses, then join the resulting duplicate emails with your table to fetch the ids:

SELECT id FROM my_table NATURAL JOIN (
  SELECT email FROM my_table GROUP BY email HAVING COUNT(*) > 1
) t
Sign up to request clarification or add additional context in comments.

2 Comments

Looks great, thanks. However, when I do while($row = mysql_fetch_array($result)) I get "Resource Id #2".... How do I set this up correctly?
Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.