سؤال

How can i make only numeric order by when the column containing alphanumeric characters in mysql ?

column (name) is unique field.

my table contains the records,

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

The results must be like this,

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

When I am trying this query Select * from test order by name, I am getting the results order by alpha characters only. How do I get this ?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top