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

https://blog.csdn.net/smile514ad/article/details/128965430

 

 

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

A表:t_active


B表:t_company


2.先查询B表t_company

select id, company_name, contact, contact_phone,actives,company_nature , mechanism from t_company where id =6
1
结果:


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

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

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')
1
2
3
4
5


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')
1
2
3
4
5


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
————————————————
版权声明:本文为CSDN博主「惟C先生」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/smile514ad/article/details/128965430

posted @ 2023-02-23 11:29  A汉克先生  阅读(126)  评论(0编辑  收藏  举报