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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章