简体   繁体   中英

From comma separated list to individual item result set. *mysql

I'm doing some data migration from a horribly designed database to a less horribly designed database. There is a many to many relationship that has a primary key in one table that corresponds to a comma separated list in another.

FK_ID | data
-------------
1,2   | foo
3     | bar
1,3,2 | blarg

Is there a way to output the FK_ID field with each comma separated element as a single line in the result set?

result set
FK_ID | data
-------------
1     | foo
2     | foo
3     | bar
1     | blarg
2     | blarg
3     | blarg

I'm thinking this would require some sort of recursive query which I don't think mysql has.

Thanks in advance.

For me the easiest way to do this would be to write a script that queries the source table and inserts the records into the target table.

Pseudocode:

query = "select * from sourcetable";
get a reader object;
while reading()
{
    orig_FK = reader(FK_ID);
    orig_data = reader(data);
    orig_FK_array = orig_FK split by comma
    foreach(ID in orig_FK_array)
    {
        query = "insert into targettable (ID, data) values (@ID, @Data);";
        add parameters;
        execute query;
    }
}

If you have a Numbers/Tally table, which is a table with a sequential list of integers, you can do it in a single query.

Select Substring(T.FK_ID
   , N.Value
   , CharIndex(',', T.FK_ID + ',', N.Value) - N.Value)
  , T.Data
From Numbers As N
 Cross Join Table As T
Where N.Value <= Len(T.FK_ID)
 And Substring(',' + T.FK_ID, N.Value, 1) = ','

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM