简体   繁体   中英

how to sort a column with different data sets in mysql

I have a column with values such as

title
------
aaa 3
bbb 5
bbb 6
yyy 1
yyy 2
bbb 8
bbb 12
aaa 1
aaa 2
bbb 14
bbb 3
bbb 4
yyy 3
aaa 4
aaa 5
aaa 6
aaa 8
aaa 12
aaa 14
yyy 4

I would like my results to be like this

title
------
aaa 1
aaa 2
aaa 3
aaa 4
aaa 5
aaa 6
aaa 8
aaa 12
aaa 14
bbb 3
bbb 4
bbb 5
bbb 6
bbb 8
bbb 12
bbb 14
yyy 1
yyy 2
yyy 3
yyy 4

I have gone through similar questions asked on stack overflow before and one very close solution I found was SELECT title FROM table ORDER BY LENGTH(title), title though it did't work for me since it only sorts from 0-9 first for all data sets then the rest follow. ie.

aaa 1
aaa 2
aaa 3
aaa 4
aaa 5
aaa 6
aaa 8
bbb 3
bbb 4
bbb 5
bbb 6
bbb 8
yyy 1
yyy 2
yyy 3
yyy 4
aaa 12
aaa 14
bbb 12
bbb 14

Suggestions would be appreciated.

Split the string at the space, and order by each part.

ORDER BY SUBSTRING_INDEX(title, ' ', 1), 0+SUBSTRING_INDEX(title, ' ', -1)

0+ will convert the second part to a number, so it will be sorted numerically.

DEMO

ORDER BY LENGTH(title), title

is only appropriate if all the prefixes are the same and you just want to order by a number at the end.

You wnat something like this, to split your data in to the two parts, which can be categorized dn the sorted by

You will have to chekc with your actual data, if the substring and the orde4r still fit, that can only you test with your data

CREATE TABLE Table1 (title varchar(6)); INSERT INTO Table1 (title) VALUES ('jan 3'), ('mar 5'), ('mar 6'), ('oct 1'), ('oct 2'), ('mar 8'), ('mar 12'), ('jan 1'), ('jan 2'), ('mar 14'), ('mar 3'), ('mar 4'), ('oct 3'), ('jan 4'), ('jan 5'), ('jan 6'), ('jan 8'), ('jan 12'), ('jan 14'), ('oct 4');
 SELECT CONCAT(title1,' ',Title2) title FROM ( SELECT title1,Title2,if (title2 < 11,1,if (title2 >= 11 AND title2 <21,2,3)) orderby FROM (SELECT SUBSTRING_INDEX(title,' ',1) title1,SUBSTRING_INDEX(title,' ',-1) + 0 title2 FROM Table1 ORDER By title1,title2) t1 ) t2 ORDER BY orderby, title1,title2
 |  title | |:----- |  |  jan 1 |  |  jan 2 |  |  jan 3 |  |  jan 4 |  |  jan 5 |  |  jan 6 |  |  jan 8 |  |  mar 3 |  |  mar 4 |  |  mar 5 |  |  mar 6 |  |  mar 8 |  |  oct 1 |  |  oct 2 |  |  oct 3 |  |  oct 4 |  |  jan 12 |  |  jan 14 |  |  mar 12 |  |  mar 14 | 

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM