Typically, row-to-column transformation can be achieved using group_concat
;
Column-to-row transformation can be indirectly achieved using union all
.
For example:
If you have a string “a,b,c” that needs to be split into multiple rows, you can perform the following operations.
- First step, implement the split function (using the
SUBSTRING_INDEX
function):
mysql> select SUBSTRING_INDEX('a,b,c',',',1),SUBSTRING_INDEX(SUBSTRING_INDEX('a,b,c',',',2),',',-1),SUBSTRING_INDEX('a,b,c',',',-1);
+--------------------------------+--------------------------------------------------------+---------------------------------+
| SUBSTRING_INDEX('a,b,c',',',1) | SUBSTRING_INDEX(SUBSTRING_INDEX('a,b,c',',',2),',',-1) | SUBSTRING_INDEX('a,b,c',',',-1) |
+--------------------------------+--------------------------------------------------------+---------------------------------+
| a | b | c |
+--------------------------------+--------------------------------------------------------+---------------------------------+
1 row in set (0.00 sec)
- Second step, column-to-row transformation (using
union
):
mysql> select SUBSTRING_INDEX('a,b,c',',',1) union select SUBSTRING_INDEX(SUBSTRING_INDEX('a,b,c',',',2),',',-1) union select SUBSTRING_INDEX('a,b,c',',',-1);
+--------------------------------+
| SUBSTRING_INDEX('a,b,c',',',1) |
+--------------------------------+
| c |
| b |
| a |
+--------------------------------+
3 rows in set (0.01 sec)