mysql将一个字符转换成多个字符,在MySQL中将定界字符串转换为多个值

这篇博客讨论了如何处理遗留的MySQL表,其中包含一个客户端标识和以逗号分隔的项目列表。用户要求能够编辑这个逗号分隔的字符串,并且需要一个报告表格将这些值分解成单独的行。由于这个查询每月仅运行一次,但必须保持最新,所以创建触发器来实时更新是不合适的。作者提供了一个通过连接整数表并检查逗号位置来拆分字符串的查询示例,但可能效率不足以用于实际操作。
摘要由CSDN通过智能技术生成

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". This is legacy stuff and the user insists on being able to edit a comma delimited string.

They now have a requirement for a report table with the above broken into separate rows, e.g.

"xyz001", "foo"

"xyz001", "bar"

"xyz001", "baz"

Breaking the string into substrings is easily doable and I have written a procedure to do this by creating a separate table, but that requires triggers to deal with deletes, updates and inserts. This query is required rarely (say once a month) but has to be absolutely up to date when it is run, so e.g. the overhead of triggers is not warranted and scheduled tasks to create the table might not be timely enough.

Is there any way to write a function to return a table or a set so that I can join the identifier with the individual items on demand?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值