0

I have a a table containing a list of email addresses. I want to select a subset of the email addresses but I want the ORDER BY statement to rotate through the domain portion of the email address, feeding them every other one.

Example Table:

+----+-------------------+-------+
| id | email             | name  |
+----+-------------------+-------+
| 1  | bob@gmail.com     | Bob   | 
| 2  | tom@gmail.com     | Tom   |
| 3  | greg@gmail.com    | Greg  |
| 4  | lisa@gmail.com    | Lisa  |
| 5  | sally@yahoo.com   | Sally |
| 6  | aaron@yahoo.com   | Aaron |
| 7  | tim@yahoo.com     | Tim   |
| 8  | wanda@hotmail.com | Wanda |
| 9  | smith@hotmail.com | Smith |
| 10 | mark@hotmail.com  | Mark  |
+----+-------------------+-------+

I am parsing the domain portion of the email using substring_index(email, '@', -1).

I would run a query something like:

SELECT id, 
    email, 
    name 
FROM emails 
ORDER BY substring_index(email, '@', -1) 
    [something here to rotate every other result], 
    id ASC

And I would want the results to look like this:

+----+-------------------+-------+
| id | email             | name  |
+----+-------------------+-------+
| 1  | bob@gmail.com     | Bob   | 
| 8  | wanda@hotmail.com | Wanda |
| 5  | sally@yahoo.com   | Sally |
| 2  | tom@gmail.com     | Tom   |
| 9  | smith@hotmail.com | Smith |
| 6  | aaron@yahoo.com   | Aaron |
| 3  | greg@gmail.com    | Greg  |
| 10 | mark@hotmail.com  | Mark  |
| 7  | tim@yahoo.com     | Tim   |
| 4  | lisa@gmail.com    | Lisa  |
+----+-------------------+-------+

Is this something possible to iterate through an item during ORDER BY?

Any advice/insight would be GREATLY appreciated :)

Gharbad The Weak
  • 1,541
  • 1
  • 17
  • 39
syntax
  • 21
  • 3

1 Answers1

1

You don't mention which version of MySQL you are using, so I'll assyume it's a modern one (8.x).

You can do:

select id, email, name,
from (
  select id, email, name,
    substring_index(email, '@', -1) as dom,
    row_number() over(partition by substring_index(email, '@', -1) 
                      order by name) as rn
  from emails
) x
order by rn, dom
The Impaler
  • 45,731
  • 9
  • 39
  • 76