SQL character fields sort by numeric fields _mysql

Source: Internet
Author: User
Tags abs

This is a long time before the problem, wrote a WP plugin: WordPress voting plug-in Ludou simple Vote, because some users need a vote, so need to use a SQL to read the list of the articles sorted by score.

Ludou simple vote's vote results are stored in a custom column in the WordPress Postmeta, the score is stored in the Meta_value field, and the Meta_value field type is Longtext, If you want to sort by using the following SQL query statement directly:

Copy Code code as follows:
ORDER BY ' Meta_value '

Then the results sorted by score may be:
1
10
11
123
1234
2
25
253
3

Because it is in alphabetical order, so 123 ranked in front of 2, obviously not in line with our requirements, then how can we expect the number of orders in order? Here are two ways to do this.

First, the use of MySQL cast function, conversion field format

Here we convert the Meta_value field to the field decimal of the numeric type, and then sort:

Copy Code code as follows:
Order by CAST (' Meta_value ' as DECIMAL)

It is important to note that the value of the Meta_value field you want to sort must all be convertible to a number, otherwise there will be an error.

Second, use the MySQL absolute value function abs

Using the MySQL absolute value function abs, it tells MySQL to use absolute value to handle this field:

Copy Code code as follows:
Order by ABS (' Meta_value ')

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.