I’m trying to get a comma separated list of values from one table into a new table as separate rows. Without losing key-value relations.
Table 1 (original data)
key | values |
---|---|
key1 | val1,val2,val3,val4 |
key2 | val1,val2,val3,val4 |
Table 2 (new data)
key | value |
---|---|
key1 | val1 |
key1 | val2 |
key1 | val3 |
key1 | val4 |
key2 | val1 |
key2 | val2 |
etc… |
I have no idea how to do this in MYSQL. Not a clue where to start or how to even Google it.
2
Answers
Try using string splitting functions along with a cross apply.
Like this.
INSERT INTO Table2 ([key], value) SELECT t1.[key], s.value FROM Table1 t1 CROSS APPLY STRING_SPLIT(t1.[values], ',') s;
Here a sample for you. You can also found this by google
create a table like this
fill it
SELECT it
query
result