Converting delimited string to multiple values in mysql

后端 未结 5 1817
逝去的感伤
逝去的感伤 2020-12-11 18:40

I have a mysql legacy table which contains an client identifier and a list of items, the latter as a comma-delimited string. E.g. \"xyz001\", \"foo,bar,baz\". T

5条回答
  •  -上瘾入骨i
    2020-12-11 19:11

    This is called walking a string. Here's an example of how you might do it with the specs provided:

    You'll need to create a table which contains as many integers as the length of the field + 1. So if the field's length is 255, you will need 256 records which just contain a single number from 0-255.

    int_table:

    +---+
    | i |
    +---+
    | 0 |
    | 1 |
    | 2 |
    | 3 |
    | 4 |
    | 5 |
    | 6 |
    +---+
    

    Next, you will need a query which joins on this table and checks if a comma exists in that location or not. (I called your table legacy_table with the fields client and items, respectively.)

    select 
      legacy_table.client, 
      substring(
        legacy_table.items, 
        int_table.i + 1, 
        if(
          locate(',', legacy_table.items, int_table.i + 1) = 0, 
          length(legacy_table.items) + 1, 
          locate(',', legacy_table.items, int_table.i + 1)
        ) - (int_table.i + 1)
      ) as item
    from legacy_table, int_table
    where legacy_table.client = 'xyz001'
      and int_table.i < length(legacy_table.items)
      and (
        (int_table.i = 0) 
        or (substring(legacy_table.items, int_table.i, 1) = ',')
      )
    

    It may not be efficient enough for you to actually use it, but I thought I'd present it as an example just so you know what is available.

提交回复
热议问题