MySQL Database text field sort Implementation statement

Source: Internet
Author: User
In MySQL, the default text field is sorted by the first character of the text field, that is, if a table structure is as follows:

If you sort the field by default for this text type, such as SELECT * FROM table ORDER by F1 ASC. The results may be as follows:
Find that MySQL sorts the fields of type text to just the first character, not the result we expected (sorted by number size).
So if you want to solve this problem, we can use a built-in function of MySQL: cast,cast (expression as data_type). Cast is an explicit type conversion function that converts the first argument to the type set by the second argument, the first argument can be a field, or another syntax-compliant expression, the second parameter is the target type, and can be of the following types:
binary[(N)]
char[(N)]
DATE
Datetime
DECIMAL
Signed [INTEGER]
Time
UNSIGNED [INTEGER]
So, for the field we want to sort, we need to convert this field to an integral type, such as signed. The corresponding MySQL statement can be this:
The code is as follows Copy Code
SELECT * FROM Table order by cast (F1 as signed) ASC;
Or you can do this:
The code is as follows Copy Code
Select CAST (F1 as signed) as F2 ORDER by F2 ASC

The effect is as follows:

In this way, we have reached our goal.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.