Alphanumeric Order By in Mysql

隐身守侯 提交于 2019-11-29 11:56:28
Mark Byers

Assuming your strings always end with 3 digits you could use RIGHT:

SELECT id, name
FROM Table1
ORDER BY RIGHT(name, 3);

Result:

1, 'ab001'
3, 'aa002'
8, 'ac003'
4, 'ac004'
7, 'aa005'
6, 'ba006'
2, 'ab010'
5, 'ba015'

MySQL doesn't have support for functional indexes, so this query will be relatively slow. It would be better to redesign your database (e.g. store the number separately) so that ordering on the value of a function isn't necessary.

I would do this way:

select id, name from Table1 order by names + 0, names;

without ordering:

mysql> select * from alpha;
+---+-------+
| i | name  |
+---+-------+
| 1 | ab001 |
| 2 | ab010 |
| 3 | aa002 |
| 4 | cc001 |
| 5 | cb010 |
| 6 | aaa02 |
+---+-------+
6 rows in set (0.00 sec)

With my query:

mysql> select i, name from alpha order by name + 0, name;
+---+-------+
| i | name  |
+---+-------+
| 3 | aa002 |
| 6 | aaa02 |
| 1 | ab001 |
| 2 | ab010 |
| 5 | cb010 |
| 4 | cc001 |
+---+-------+
6 rows in set (0.00 sec)

I had a slightly different issue, but the second example worked for me. I'd vote it up, but I just got started here.

I was dealing with a single varchar column which could contain any kind of information, but it needed to sort properly no matter what was in it:

So my column could contain info such as:

AB CD EF GH

or

01 02 03 04

The answer from Xavier caused it to be in alphabetical order when the information was all alphabetical, or numeric when the info was numeric.

Thanks

Thanks!

If you have the first X characters as letters and the rest as numbers and the alpha characters vary, you are far better off changing your structure to put this data in two columns - one for the intital letters and one for the numbers. Now you don't have to do coanversions every time you want to order, you just order on the letter columns first, then the numeric column. A redesign of your structure is truly the better way to do this espcially if you wil be ordering often or if you have a large dataset.

You could even leave the current field as the PK and have a trigger separate out to the two new fields. This way, the data is put in a format that can be ordered automatically when it is entered or updated, all current code will still work, but you can refactor to use more performant ordering.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!