Several times ,I have need to sort alphanumeric rows in a database by number (i.e. emp1, emp2, emp3,emp10,emp15 etc.) in Project . you want to sorting alphanumeric using mysql query. Follwing code use.
The Data
For our purposes, we’ll be using the following table:
Table: sorting_image
-------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
-------------------------- -------------
| image1 | 1 |
| image2 | 2 |
| image3 | 3 |
| image4 | 4 |
| image5 | 5 |
| image6 | 6 |
| image7 | 7 |
| image8 | 8 |
| image9 | 9 |
| image10 | 10 |
| image11 | 11 |
| image12 | 12 |
-------------------------- -------------
Sorting by the column idnumber,
Query: SELECT alphanumeric, idnumber
FROM sorting_image
ORDER BY idnumber
-------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
-------------------------- -------------
| image1 | 1 |
| image2 | 2 |
| image3 | 3 |
| image4 | 4 |
| image5 | 5 |
| image6 | 6 |
| image7 | 7 |
| image8 | 8 |
| image9 | 9 |
| image10 | 10 |
| image11 | 11 |
| image12 | 12 |
-------------------------- -------------
if you sorting by the alphanumeric column, we get unexpected results:
Query: SELECT alphanumeric, idnumber
FROM sorting_image
ORDER BY alphanumeric
-------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
-------------------------- -------------
| image1 | 1 |
| image10 | 10 |
| image11 | 11 |
| image12 | 12 |
| image2 | 2 |
| image3 | 3 |
| image4 | 4 |
| image5 | 5 |
| image6 | 6 |
| image7 | 7 |
| image8 | 8 |
| image9 | 9 |
-------------------------- -------------
Solution
Obviously, desired Results not come. Since we’re sorting alphabetically, the entries are actually in the correct order, but we need to find a way to sort numerically as called Natural Sorting . Please use in mysql query "sort by length" column value.Query: SELECT alphanumeric, idnumber
FROM sorting_image
ORDER BY LENGTH(alphanumeric), alphanumeric
-------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
-------------------------- -------------
| image1 | 1 |
| image2 | 2 |
| image3 | 3 |
| image4 | 4 |
| image5 | 5 |
| image6 | 6 |
| image7 | 7 |
| image8 | 8 |
| image9 | 9 |
| image10 | 10 |
| image11 | 11 |
| image12 | 12 |
-------------------------- -------------
No comments:
Post a Comment