tags:

views:

180

answers:

2

I need to use natural sorting with a MySQL result since it currently sorts my INT values as follows:

  • 1
  • 123
  • 1256
  • 22
  • 231

[etc]

While I would need it to sort like

  • 1
  • 22
  • 231
  • 1256

I know of the "natsort" function, but it does not work for a MySQL query result. How can I sort (naturally), is it possible to do this within the query?

Thanks for the help!

EDIT: Example query $result = mysql_query("SELECT * FROM forums ORDER BY 'posts' DESC;");

Not entirely sure if my use of DESC there is valid, but it doesn't throw an error so it must be fine. Unfortunately, it seems changing DESC to ASC also has no effect...

+1  A: 

The query you've posted there is sorting by a constant string expression, rather than a column name or position. Either use backticks to quote, or take out the quotes:

SELECT * FROM forums ORDER BY `posts` DESC

or maybe

SELECT * FROM forums ORDER BY posts DESC

Would explain why changing between ASC and DESC has no effect.

Initial Answer Was:

The sort order you describe suggests the INT values are actually being stored as a character type (or maybe converted to character before sorting).

Check whether you are storing the data in a numeric or character type. If possible use a numeric type, then the natural sort order will be as you require. If you can't change the underlying data type to be INT, then you can do this in your query (e.g. using CAST), probably at cost of performance.

martin clayton
Stored as INT(11), what can I do to fix any issues?
Cyclone
Its already stored as a numeric type
Cyclone
Oh wow, never knew that. Thanks for the help, that fixed it right away. That is really useful to know!
Cyclone
For interest sake, you can also do a natural sort with "order by fieldname+0" if fieldname is a character type.
Matt H
A: 

This question has an answer for MySQL that I have used.

Marius
No idea how to implement a MySQL module, its a "shared hosting" type account. Meaning, I don't have access to MySQL itself.
Cyclone
All you need to do is run the code provided as an sql query. If you have phpMyAdmin available, then open it up, click on the sql button on the left hand side, and paste the entire thing into it.
Marius