MySQL按顺序排列字符串

备注:测试数据库版本为MySQL 8.0

如需要scott用户下建表及录入数据语句,可参考:
scott建表及录入数据sql脚本

一.需求

对表中的字符串,按字母顺序排列其中的各个字符。
例如:
±-------+
| ename |
±-------+
| SMITH |
| ALLEN |
| WARD |
| JONES |
| MARTIN |
| BLAKE |
| CLARK |
| SCOTT |
| KING |
| TURNER |
| ADAMS |
| JAMES |
| FORD |
| MILLER |
±-------+

需要结果如下所示:
±---------±---------+
| old_name | new_name |
±---------±---------+
| ADAMS | AADMS |
| ALLEN | AELLN |
| BLAKE | ABEKL |
| CLARK | ACKLR |
| FORD | DFOR |
| JAMES | AEJMS |
| JONES | EJNOS |
| KING | GIKN |
| MARTIN | AIMNRT |
| MILLER | EILLMR |
| SCOTT | COSTT |
| SMITH | HIMST |
| TURNER | ENRRTU |
| WARD | ADRW |
±---------±---------+

二.解决方案

使用MySQL自带的group_concat可以很轻易的解决这个问题

代码:

select ename, group_concat(c order by c separator '')
  from (
select ename,substr(a.ename,iter.pos,1) c
  from emp a,
       ( select id pos from t10 ) iter
where iter.pos <= length(a.ename)
       ) x
gorup by ename

测试记录:

mysql> select ename old_name,
    ->        group_concat(c order by c separator '') new_name
    ->   from (
    -> select ename,substr(a.ename,iter.pos,1) c
    ->   from emp a,
    ->        ( select id pos from t10 ) iter
    -> where iter.pos <= length(a.ename)
    ->        ) x
    -> group by ename;
+----------+----------+
| old_name | new_name |
+----------+----------+
| ADAMS    | AADMS    |
| ALLEN    | AELLN    |
| BLAKE    | ABEKL    |
| CLARK    | ACKLR    |
| FORD     | DFOR     |
| JAMES    | AEJMS    |
| JONES    | EJNOS    |
| KING     | GIKN     |
| MARTIN   | AIMNRT   |
| MILLER   | EILLMR   |
| SCOTT    | COSTT    |
| SMITH    | HIMST    |
| TURNER   | ENRRTU   |
| WARD     | ADRW     |
+----------+----------+
14 rows in set (0.00 sec)

mysql>

你可能感兴趣的:(#,MySQL,CookBook,MySQL从小工到专家之路,mysql,sql,顺序排列字符串,group_concat,substr)