Let’s say I have a table like this:
name | address
------------+----------------
JOHN SMITH | 123 FAKE ST
JANE SMITH | 123 FAKE ST
DAN JOHNSON | 456 WHATEVER RD
Now let’s say I create a view where I do GROUP BY address, resulting in something like this:
name | address | group_id
-----------------------+-----------------+---------
JOHN SMITH, JANE SMITH | 123 FAKE ST | 1
DAN JOHNSON | 456 WHATEVER RD | 2
Is there a way, using just SQL, to “expand” the results of that grouping, like this?
name | address | group_id
------------+-----------------+---------
JOHN SMITH | 123 FAKE ST | 1
JANE SMITH | 123 FAKE ST | 1
DAN JOHNSON | 456 WHATEVER RD | 2
Yes, as ypercube noted it is possible and you will need a SUBSTRING_INDEX function. You will also need to regenerate rows which is tricky since mysql does not support recursive queries.
You can do a workaround, here’s a solution assuming max 3 records just to illustrate:
The conceptual ugliness and deficiencies of the above approach is one of the reasons why you are advised never to do this as a normal, designed procedure in the system (performance will also never be good): aggregating records is considered a part of presentation layer and not to be used to write anything back into the database and always be able to retrieve the records from the unaggregated source.
When you deviate from the above rule you will have to take approach similar to the above (other database which support recursive queries might do it nicer, but there is no magic silver bullet for the fact that the query will not be able to use indexes on column name efficiently).
EDIT:
I used the term aggregating for the
group_concat(and similar), which is not specific enough. It would be better to say – storing multiple values in single field (repeating group in a single column).