有些列的值是逗号分隔的id,例如用户id:1,2,3,想要把这些id转成对应的文字,本文介绍转换方法。


方法一:
借助mysql.help_topic,参考我的另一篇博客:MySQL列转行-CSDN博客
方法二:
借助SUBSTRING_INDEX,先按逗号拆开,再转换成文字,最后拼接:
sql
select w.id workorderId,
w.desc workorderDesc,
concat(if(s1.name is null , '' ,s1.name),
if(s2.name is null or s2.name = s1.name,'',concat(',',s2.name)),
if(s3.name is null or s3.name = s2.name,'',concat(',',s3.name)),
if(s4.name is null or s4.name = s3.name,'',concat(',',s4.name)),
if(s5.name is null or s5.name = s4.name,'',concat(',',s5.name))
) processors
from workorder w
left join staff s1 on s1.id=SUBSTRING_INDEX(w.processors,',',1)
left join staff s2 on s2.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',2),',',-1)
left join staff s3 on s3.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',3),',',-1)
left join staff s4 on s4.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',4),',',-1)
left join staff s5 on s5.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',5),',',-1)

注意:其中的比较"s2.name = s1.name"等是必须的,因为SUBSTRING_INDEX超出元素个数以后,会一直取最后一个元素,以下给出反例,注意避免:
sql
select w.id workorderId,
w.desc workorderDesc,
concat(if(s1.name is null , '' ,s1.name),
if(s2.name is null,'',concat(',',s2.name)),
if(s3.name is null,'',concat(',',s3.name)),
if(s4.name is null,'',concat(',',s4.name)),
if(s5.name is null,'',concat(',',s5.name))
) processors
from workorder w
left join staff s1 on s1.id=SUBSTRING_INDEX(w.processors,',',1)
left join staff s2 on s2.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',2),',',-1)
left join staff s3 on s3.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',3),',',-1)
left join staff s4 on s4.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',4),',',-1)
left join staff s5 on s5.id=SUBSTRING_INDEX(SUBSTRING_INDEX(w.processors,',',5),',',-1)

方法三:
借助substr,适用于id长度固定的情况,如果id不固定,不可以使用。
left(w.processors,<id长度>)
substr(w.processors,<开始截取位置>,<id长度>)
sql
select w.id workorderId,
w.desc workorderDesc,
concat(if(s1.name is null , '' ,s1.name),
if(s2.name is null,'',concat(',',s2.name)),
if(s3.name is null,'',concat(',',s3.name)),
if(s4.name is null,'',concat(',',s4.name)),
if(s5.name is null,'',concat(',',s5.name))
) processors
from workorder w
left join staff s1 on left(w.processors,1) = s1.id
left join staff s2 on substr(w.processors,3,1) = s2.id
left join staff s3 on substr(w.processors,5,1) = s3.id
left join staff s4 on substr(w.processors,7,1) = s4.id
left join staff s5 on substr(w.processors,9,1) = s5.id
