dongshanyan0322 2014-03-20 19:12
浏览 48
已采纳

如何使用特定的索引值对数组进行排序?

I have written a function to get all the users details from a 2 table. This is the code

//get all the diff each users
    $db->query("SELECT DISTINCT (user_fb_id )FROM users_points WHERE users_points.match_id >= '$matchId'");
    $distinctUsers = $db->resultsArray;

        foreach($distinctUsers as $key=>$user){

            $db->query("SELECT SUM(points) AS totalPoints FROM users_points WHERE user_fb_id = '{$user['user_fb_id']}' AND match_id >= '$matchId' ORDER BY totalPoints DESC");

            $result[$key]['user_fb_id'] = $user['user_fb_id'];
            $totalPoint = $db->resultsArray;
            $result[$key]['totalPoints'] = $totalPoint[0]['totalPoints'];
            $db->query("SELECT user_firstName, user_lastName FROM user WHERE user_fb_id = '{$user['user_fb_id']}'");

            $userDetail = $db->resultsArray;
            $result[$key]['user_name'] = $userDetail[0]['user_firstName'].' '.$userDetail[0]['user_lastName'];

        }

    return $result;

using this function i can get users details. but not in an order. It should be sorted DESC.

How can to write single query for this function, instead of having 3 quires.?

or else,

how to sort the array 'totalPoints'?

  • 写回答

1条回答 默认 最新

  • dongxun6458 2014-03-20 19:48
    关注

    Here's a basic join query to combine all three into one.

    SELECT DISTINCT u.user_fb_id, SUM(u.points) as total_points, r.user_firstname, r.user_lastname 
    FROM user_points u, user r 
    WHERE u.match_id >= 2300 AND r.user_id = u.user_fb_id 
    ORDER BY total_points DESC;
    

    This may not be the most optimized query, but it's oodles faster than looping with three. Definitely play around with it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题