mysql中对某个字段按某个字符分割,并转成行数据

1.背景

        在开发过程中碰到一个项目号包含多个供应商,但其表结构和存储如下:

        表结构 |--------item_num------|------item_name-------|---------relation_supplier---------|

其中relation_suppler 存储的是供应商id,多个用','号隔开。

现在有个需求就是我需要写一个接口在前端做选择,类似一个下面的表格

项目供应商
编号001-湖南xx项目供应商1
编号001-湖南xx项目供应商2
编号001-湖南xx项目供应商3

即需要将表中的relation_supplier 字段按 ',' 号隔开并与原记录的项目组成一行记录。

SQL 实现1

select
	t.sap_item_num ,
	t.item_name ,
	t.whether_forbidden ,
	replace(
 replace( 
	replace(substring_index(substring_index(t.relation_supplier, ',', a.rownum), ',' ,- 1), '[', '') 
 		, ']', '')
 		, '"', '')
		as relation_supplier
from
	project_information_settings t,
	(
	select
			@rownum := @rownum + 1 as rownum
	from
			project_information_settings m,
			(
		select
			@rownum := 0) n
	) a
where
	t.is_delete = 'undelete'
	and a.rownum <= (
	length(t.relation_supplier) - length(
		replace (t.relation_supplier, ',', '')
	) + 1
)

上面 replace部分只是将原字段中被','号分割后存在的 [ ," ,] 号去掉,在mysql 8中可以用函数 regex_replace, 本人所用mysql版本较低,所以用了多个replace。

另一种写法

select
	pis.sap_item_num ,
	pis.item_name,
	pis.whether_forbidden,
	replace(
 replace(
 replace(
	substring_index(substring_index(pis.relation_supplier , ',', b.help_topic_id + 1), ',',-1)
	,'[','')
	, ']', '')
 		, '"', '')
	as supplier_id
from
	project_information_settings pis
join mysql.help_topic b 
on
	b.help_topic_id <(length(pis.relation_supplier) - length(replace(pis.relation_supplier, ',', '')) + 1)
 where pis.is_delete = 'undelete'
order by
	pis.id_

其中 mysql.help_topic 表示mysql中存在的表 , is_delete 是我业务表的一个是否删除的标志字段

效果

  • 12
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值