Skip to content
Advertisement

MYSQL How do I Select all emails from a table but limit number of emails with the same domain

As the topic sugests I want to select all emails in the list. But limit the number of emails with the same domain.

Lets say i have 500 gmail adressses.

And 2 example.com adresses.

.. and so on..

I want to just grab 2 of each adress with the same domain.

With this string i can select the number of domains that accurs on each domain so maybe I can do something with this string.

SELECT substring_index(email, '@', -1), COUNT(*) FROM emaillist GROUP
BY substring_index(email, '@', -1);

Please help!

Advertisement

Answer

SELECT
  MIN(email) AS address1
  IF(MAX(email)==MIN(email),NULL,MAX(email)) AS address2
FROM emaillist
GROUP BY substring_index(email, '@', -1);

and if you want them in one column

SELECT MIN(email) AS address1
FROM emaillist
GROUP BY substring_index(email, '@', -1)
UNION
SELECT MAX(email) AS address1
FROM emaillist
GROUP BY substring_index(email, '@', -1)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement