How to sort SQL complex fields by Numeric Fields

Source: Internet
Author: User

This was a long time ago problem. Last year I wrote a WP plug-in: WordPress voting plug-in Ludou Simple Vote. Some users need a Vote ranking, therefore, you need to use an SQL statement to read the list of articles sorted by score.

The Ludou Simple Vote Voting score is stored in postmeta of WordPress in the form of custom columns. The score is stored in the meta_value field, while the meta_value field type is longtext, use the following SQL query statement to sort data:

Copy codeThe Code is as follows: order by 'meta _ value'

The result of sorting by score may be:
1
10
11
123
1234
2
25
253
3

Because it is in alphabetical order, 123 is at the top of 2, which obviously does not meet our requirements. How can we sort the data in the order we expected? The following two methods are described.

I. Use the cast function of MySQL to convert the Field Format

Here we convert the meta_value field to the DECIMAL field of the numerical type, and then sort it:

Copy codeThe Code is AS follows: order by cast ('meta _ value' as decimal)

Note that the values of the meta_value field to be sorted must be convertible to numbers; otherwise, errors may occur.

Ii. Use the MySQL absolute value function ABS

The MySQL absolute value function ABS tells MySQL to process this field using the absolute value:

Copy codeThe Code is as follows: order by abs ('meta _ value ')

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.