Mysql中以逗号分割的id转换成文字

文章讲述了在MySQL数据库中,如何处理B表中以逗号分隔的ID字符串,将其转换为A表中的相关名称。通过使用find_in_set函数查找ID,concat和if函数处理父级关系,以及group_concat函数合并结果,最终形成查询语句,将B表中的actives字段转换为A表中name字段的连接字符串,父级名称用“-”分隔。
摘要由CSDN通过智能技术生成

Mysql中以逗号分割的id转换成文字

场景:B表中的字段actives存储的是以逗号分割的字符串,其内容是A表中的id,A表示类似于菜单的父子级结构;现在要求查询B表的时候将actives字段转换对应A表中的的name,若存在父级则用“-”连接。
1.新建A表和B表

A表:t_active在这里插入图片描述

在这里插入图片描述
B表:t_company
b
在这里插入图片描述
2.先查询B表t_company

select id, company_name, contact, contact_phone,actives,company_nature , mechanism from t_company where id =6

结果:
在这里插入图片描述

3.使用函数find_in_set查询actives在A表中对应的name

select ta.name from t_active where FIND_IN_SET(ta.id,'3,10,12')

在这里插入图片描述
4.若存在父级的则用“-”连接,id为10 和12的是存在父级的;使用if(条件,val1,val2)和 concat(a,b)函数

select concat(
     if(ta.parent_id = 0,'', concat(
        (select name from t_active where id = ta.parent_id),'-')
     ),ta.name) actives
from t_active ta where FIND_IN_SET(ta.id,'3,10,12')

在这里插入图片描述

5.将多行合并成一行,使用group_concat函数

select group_concat(concat(
     if(ta.parent_id = 0,'', concat(
        (select name from t_active where id = ta.parent_id),'-')
     ),ta.name)) actives
from t_active ta where FIND_IN_SET(ta.id,'3,10,12')

在这里插入图片描述

5.将第2步sql中的actives替换成第4步的sql

select tc.id, tc.company_name, tc.contact, tc.contact_phone,tc.company_nature ,tc.mechanism,
(select 
	group_concat(
		concat(
			if(ta.parent_id = 0,'', concat(
        (select name from t_active where id = ta.parent_id),'-'
				)
			),ta.name
		)
	) actives
from t_active ta where FIND_IN_SET(ta.id,tc.actives)
) actives
from t_company tc where tc.id =6

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值