Jump to content

php sorting problem usng SQL ORDER BY


peterjc

Recommended Posts

i have a sorting problem in php using the SQL command "ORDER BY".

 

-----------------

For example:

i want to sort this number descending: 30, 4, 50, 200.

 

so in actual case we should get: 200 , 50, 30 , 4.

 

But what i get when using the ORDER BY statement is: 50, 4, 30, 200

 

-------------------

After look a while at the incorrect result, i think the problem is because it sort using the first digit of the number.

 

Anyone know how to solve this problem?

 

Thank in advance.

Link to comment
Share on other sites

The other option is

 

ORDER BY CAST(foo AS UNSIGNED)

 

What happens when you add 0 to foo is that mysql is forced to convert foo into an integer.  After that, it is sorted as an integer.  The same happens when you explicitly cast foo to an integer using CAST().  "Cast" means "Change from one type to another".

 

The original problem is that your numbers were being sorted as strings, which is why it looked at the first character first, then second, and so on.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.