当前位置:   article > 正文

mysql 字段分割排序,MySQL-在列中用逗号分隔的字符串排序

mysql把用逗号隔开存起来的数据排序

I have table:

+-----+------------+--------------+

| id | title | numbers |

| 2 | Title 1 | 2,8,5 |

| 3 | Title 2 | 50,7,9,4 |

+-----+------------+--------------+

Is it possible to sort within the column? In this case in column numbers.

I need to output ordered numbers column as follows:

+-----+------------+--------------+

| id | title | numbers |

| 2 | Title 1 | 2,5,8 |

| 3 | Title 2 | 4,7,9,50 |

+-----+------------+--------------+

Something like:

SELECT id, title, SORT_FUNC(numbers) from table

I was looking for some function in MySQL documentation, but I found nothing.

解决方案

It is possible, but not really a good idea.

As an example, you can split a comma separated list up by generating a range of numbers and using that with SUBSTRING_INDEX to get each element. However the range of numbers needs to be as big as the max number of delimited values.

You could then use GROUP_CONCAT to join the list back together in the right order. Note that the order will be different depending on whether you have cast the split up values as numbers / integers or left them as strings.

SELECT id, title, GROUP_CONCAT(aNumber ORDER BY aNumber)

FROM

(

SELECT id, title, CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(numbers, ',', tens.acnt * 10 + units.acnt + 1), ',', -1) AS UNSIGNED) AS aNumber

FROM some_table

CROSS JOIN

(SELECT 0 AS acnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units

CROSS JOIN

(SELECT 0 AS acnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens

WHERE LENGTH(numbers) - LENGTH(REPLACE(numbers, ',', '')) >= tens.acnt * 10 + units.acnt

) sub0

GROUP BY id, title;

Demonstrated here on SQL fiddle (if SQL fiddle decides to work):-

First select is casting the values as integers to sort them numerically, 2nd one isn't casting them but just leaving them as strings, hence the sort order is different.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/268402
推荐阅读
相关标签
  

闽ICP备14008679号