Extracting results of a GROUP BY
Let's say I have a table like this:
name |开发者_如何学C 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
One option is to use SUBSTRING_INDEX()
function.
Check this blog post where a SPLIT_STRING()
function is defined: mysql-split-string-function
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:
SELECT SUBSTRING_INDEX(name, ',', 1), address, group_id
FROM aggregated a1
WHERE
UNION ALL
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name, ',', 2), ',', -1), address, group_id
FROM aggregated a2
WHERE name LIKE '%,%'
UNION ALL
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name, ',', 3), ',', -1), address, group_id
FROM aggregated a3
WHERE name LIKE '%,%,%'
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).
Use GROUP BY a.name
. Why do you want to group it by address?
You will anyway use WHERE a.address=b.address
right!
精彩评论