赞
踩
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.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。