I am working with a table that contains logs for users reported exercise distances. I want to rank users by the sum of their logged distance.
First I find all the User ID’s:
select distinct wordpress_user_id from wp_exercise_log
Then I loop through that and get the name and sum(distance) with:
foreach($users as $user) {
// DISTANCE
$user_distance = floor($wpdb->get_var( "select sum(distance) from wp_exercise_log where wordpress_user_id='$user'"));
// FULL NAME
$user_info = get_userdata($user);
$full_name = $user_info-> user_firstname . ' ' . $user_info-> user_lastname;
}
Heres my problem: Unless I append them to a multidimensional array and sort with PHP, I’m not sure how I can rank the users.
Is there a better way to select all this data and sort it with one SQL query?
Please mind
ORDER BY GROUP_FUNCTION()is always causing perfomance issues.You may consider to add some column
user_total_distanceto your users table and update it every change inwp_exercise_log.