group_concat order by 字符串的排序混乱

mysql group_concat子句使用order by 进行字符串排序时,若字符串值为数字,排序错位,比如:

mysql> select `size_group_id`, group_concat(name order by name asc) as sizes from `basic_sizes` where `size_group_id` in (2, 1) group by `size_group_id`
    -> ;
+---------------+-------------------------------------+
| size_group_id | sizes                               |
+---------------+-------------------------------------+
|             1 | 11,13,15,17,5,7,9                   |
|             2 | 26,27,28,29,30,31,32,33,34,35,36,37 |
+---------------+-------------------------------------+
2 rows in set (0.00 sec)

解决方案1:order by name+0

mysql> select `size_group_id`, group_concat(name order by name+0 asc) as sizes from `basic_sizes` where `size_group_id` in (2, 1) group by `size_group_id`;
+---------------+-------------------------------------+
| size_group_id | sizes                               |
+---------------+-------------------------------------+
|             1 | 5,7,9,11,13,15,17                   |
|             2 | 26,27,28,29,30,31,32,33,34,35,36,37 |
+---------------+-------------------------------------+
2 rows in set (0.01 sec)

解决方案2:order by length(name),name

mysql> select `size_group_id`, group_concat(name order by length(name),name asc) as sizes from `basic_sizes` where `size_group_id` in (2, 1) group by `size_group_id`;
+---------------+-------------------------------------+
| size_group_id | sizes                               |
+---------------+-------------------------------------+
|             1 | 5,7,9,11,13,15,17                   |
|             2 | 26,27,28,29,30,31,32,33,34,35,36,37 |
+---------------+-------------------------------------+
2 rows in set (0.00 sec)

 

你可能感兴趣的:(group_concat order by 字符串的排序混乱)