ORDER BY%, which is calculated inside the original while loop

I want to order the results based on the answer of the sum of mathematics in the main query of the results, here is what I mean:

My current code looks something like this:

$query = "SELECT * FROM foo WHERE foobar='{$fobo}' ORDER BY id DESC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $percent = round((100 * $row['wins'] / ($row['wins'] + $row['loses']))); echo 'blah blah blah' . $percent; } 

As you can see, I'm currently ORDER BY id:

 $query = "SELECT * FROM foo WHERE foobar='{$fobo}' ORDER BY id DESC"; 

but I want to ORDER with the answer $percent , but which is calculated inside the while loop.

I tried to create a query and put it before the main query for results:

 $p = "SELECT wins, loses FROM foo WHERE foobar='{$fobo}'"; $pr = mysql_query($p); $pow = mysql_fetch_array($pr); $percent = round((100 * $pow['wins'] / ($pow['wins'] + $pow['loses']))); 

but spitting out

Warning: mysql_fetch_array () expects parameter 1 to be a resource, boolean

I think that% calculation can be done in the main request, and not in the php sum, which I think will do it, but I don’t know what the request is.

+4
source share
3 answers

Instead of calculating the percentage value inside the loop, and then sorting using another loop, you can do this with just one query like:

 $query = "SELECT foo.*, ROUND((100 * wins / (wins + loses))) AS percentage FROM foo WHERE foobar='{$fobo}' ORDER BY percentage ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo 'blah blah blah' . $row['percentage']; } 
+5
source

You can use the column number, for example:

 select col1, col2 round((100*wins)/wins+loses) from foo where foobar='{$fobo}' group by col1, col2 order by 3 
+2
source

You can perform the calculation in your order according to the offer

 SELECT * FROM tableName ORDER BY ROUND((100*wins) / (wins+loses)) DESC 
+2
source

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


All Articles