Page 1 of 1

mysql queries question...order by division of two column

Posted: Mon May 23, 2005 8:50 am
by dmmh
in order to be able to use proper sorting functionality on my site I need my query to be modified to calculate the division of two INT values in a returned row

I need this for rating functionality, so if I would simply ORDER BY (field_rating), this wouldnt be precise enough, as it may have a value of 10 with 10 votes, which averages 1 and another row might be 9, but with 1 votes, which would mean the first scenario would be shown first, but it should be the other way around...if you know what I mean :p

my query now:

$query = 'SELECT * FROM comments'.
" INNER JOIN users_table".
" ON (users_table.userid = comments.added_by)".
" WHERE comments.mid = '$mid'".
" ORDER BY comments.$sort $order".
" LIMIT $from, $max_results";

Posted: Mon May 23, 2005 3:27 pm
by bitWISE
Why does it matter how many votes?

Posted: Mon May 23, 2005 3:47 pm
by dmmh
so one can compute a average? :dork:

Posted: Mon May 23, 2005 6:10 pm
by bitWISE
shouldnt the rating already be an average?

Posted: Tue May 24, 2005 4:51 pm
by dmmh
and this is handy how?
i could do it like that, but its more cumbersome to compute a new average when a new vote is cast (because you'd first need to multiply by numbers of votes, then sum it up, the devide again, now I just sum and divide)

im sure it can be done

Posted: Tue May 24, 2005 5:11 pm
by bitWISE
Well now that you told me you are storing the sum and not the rating that helps :p

Just do this:
if ($sort == 'rating') {
$query = 'SELECT * FROM comments'.
" INNER JOIN users_table".
" ON (users_table.userid = comments.added_by)".
" WHERE comments.mid = '$mid'".
" ORDER BY comments.rating/comments.total $order".
" LIMIT $from, $max_results";
}

Posted: Tue May 24, 2005 6:45 pm
by dmmh
thanks, figured it would be something simple nowhere to be found in some docs lol

didnt notice I forgot to mention I just use a sum, thx for the help :up:

Posted: Tue May 24, 2005 6:48 pm
by bitWISE
n/p.

I didn't really know you could do it so I fired up phpMyAdmin and tested it out.