Mysql ORDER BY numbers DESC

I have a simple mysql select query in my PHP code:

$result = mysql_query("SELECT text FROM example ORDER BY rank DESC"); while($row = mysql_fetch_array($result)) { echo $row['text'] . "<br>"; } 

and this MySql table:

  text | rank --------+-------- google | 245 --------+-------- yahoo | 32 --------+-------- bing | 12 

When I get the query results, something like this will appear:

 yahoo google bing 

I want Google to come. I think that Yahoo is primarily because it starts with a "3".

How can I make the query sort the results by the size of the numbers in the rank?

Thanks...

+4
source share
5 answers

I assume that the rank field is some type of string. Make it an int numeric type and it will be properly ordered

+9
source

The correct solution, of course, is to use the correct data type. As a workaround, you can transfer data on the fly:

 SELECT text FROM example ORDER BY rank + 0 DESC 

or

 SELECT text FROM example ORDER BY cast(rank as unsigned) DESC 
+6
source

What data type is rank in your SQL schema? Set it to a numeric type.

+3
source

Try the following:

 $result = mysql_query("SELECT * FROM example ORDER BY rank DESC"); while($row = mysql_fetch_array($result)) { echo $row['text'] . " ". $row['rank'] ."<br>"; } 

And see if the ranks are sorted correctly.

+1
source
 $result = mysql_query("SELECT * FROM `example` ORDER BY `rank` DESC"); while($row = mysql_fetch_array($result)) { echo $row['text'] ."<br>"; } 
+1
source

Source: https://habr.com/ru/post/1379685/


All Articles