I seem to come against this problem a lot, where I have data that's formatted like this:
+----+----------------------+
| id | colors |
+----+----------------------+
| 1 | Red,Green,Blue |
| 2 | Orangered,Periwinkle |
+----+----------------------+
but I want it formatted like this:
+----+------------+
| id | colors |
+----+------------+
| 1 | Red |
| 1 | Green |
| 1 | Blue |
| 2 | Orangered |
| 2 | Periwinkle |
+----+------------+
Is there a good way to do this? What is this kind of operation even called?
You could use a query like this:
Please see fiddle here. Please notice that this query will support up to 4 colors for every row, you should update your subquery to return more than 4 numbers (or you should use a table that contains 10 or 100 numbers).
I think it is what you need (stored procedure) : Mysql split column string into rows
This saved me many hours! Taking it a step further: On a typical implementation there would in all likelyhood be a table that enumerates the colours against an identitying key,
color_list
. A new colour can be added to the implementation without having to modify the query and the potentially endlessunion
-clause can be avoided altogether by changing the query to this:It is important that the Ids in table color_list remain sequential, however.
if delimiter is part of data but embedded by double quotes then how can we split it.
Example first,"second,s",third
it should come as first second,s third
notice this can be done without creating a temporary table