最近做的一个项目中,有一个码值转换的需求,需要把一个字段中串连起来的字典码值全部转换成对应的中文,网上查了下发现MySQL好像没有现成的函数能拿来用,于是只好自己动手。
比如下面这张sys_dept表,ancestors表示该组织的所有上级组织,需要把这些上级组织全部用中文+‘-’的形式串联起来。

第一个思路就是直接写sql来拼接,通过SUBSTRING_INDEX函数分割码值,GROUP_CONCAT函数拼接字符串来达到我们要的效果:
select s1.dept_id, s1.dept_name,
GROUP_CONCAT((SELECT s2.dept_name FROM sys_dept s2 WHERE s2.dept_id = SUBSTRING_INDEX(SUBSTRING_INDEX(s1.ancestors, ',', -a.id), ',', 1)) SEPARATOR '-') AS ancestors_name
from (select 1 as id union all
select 2 as id union all
select 3 as id union all
select 4 as id union all
select 5 as id union all
select 6 as id union all
select 7 as id union all
select 8 as id union all
select 9 as id union all
select 10 as id) a
INNER JOIN sys_dept s1
ON LENGTH(s1.ancestors) - LENGTH(REPLACE(s1.an

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



