0

我有 2 个 mysql 查询,一个用于获取我所有的朋友,另一个用于获取每个朋友的详细信息和积分总和。

$get_my_friends_query = mysqli_query($GLOBALS['connect'], "SELECT friend_user_id FROM tbl_friend_link WHERE tbl_friend_link.your_user_id = 1");

while($get_my_friends_result = mysqli_fetch_assoc($get_my_friends_query))
{
   $get_friend_user_details_query = mysqli_query($GLOBALS['connect'], "SELECT tbl_registered_user.user_id, tbl_registered_user.first_name, tbl_registered_user.last_name,  tbl_registered_user.profile_name, SUM(tbl_point.amount) FROM tbl_registered_user JOIN tbl_point ON tbl_registered_user.user_id = tbl_point.user_id WHERE tbl_registered_user.status = 1 AND tbl_registered_user.user_id = '" . $get_my_friends_result['friend_user_id'] ."' GROUP BY tbl_registered_user.user_id ORDER BY SUM(tbl_point.amount)");
   $get_friend_user_details_result = mysqli_fetch_assoc($get_friend_user_details_query);

   $result = array(
      "done" => "true",
      "name" => $get_friend_user_details_result['first_name'] . " " . $get_friend_user_details_result['last_name'],
      "profile_name" => $get_friend_user_details_result['profile_name'],
      "userID" => $get_friend_user_details_result['user_id'],
      "points" => $get_friend_user_details_result['SUM(tbl_point.amount)'],
      "number_friends" => mysqli_num_rows($get_my_friends_query),
      "error_message" => ""
   );
   $row_array[] = $result;
}

echo json_encode($row_array);

我正在使用第一个查询,因为我希望显示结果,无论它们是否有任何点。我想根据点的总和对结果进行排序,但是在第二个查询中正在检索信息,但是我找不到关于如何在 $row_array 上使用 usort 的合适解释。

4

3 回答 3

1

我得到它与以下工作:

function sorter($key){
    return function ($a, $b) use ($key) {
        return $a[$key] - $b[$key];
    };
}
usort($row_array, sorter('points'));
var_dump($row_array);
于 2013-07-11T10:33:31.470 回答
0

要“无论它们是否有任何点都显示”,您应该查看外部连接。Sams 在 10 分钟内自学 MySQL 的示例:

mysql>  SELECT c.name, o.order_date
    ->  FROM customers c
    ->  LEFT OUTER JOIN orders o
    ->  ON o.customer_code = c.customer_code
    ->  AND o.order_date BETWEEN '2006-02-01' AND '2006-02-28';
+-------------------------+------------+
| name                    | order_date |
+-------------------------+------------+
| Presidents Incorporated | NULL       |
| Science Corporation     | 2006-02-02 |
| Science Corporation     | 2006-02-05 |  
| Musicians of America    | 2006-02-01 |
| Musicians of America    | 2006-02-02 |
+-------------------------+------------+
5 rows in set (0.00 sec)

此外,我会使用AS关键字在查询中直接命名我想要的列,而不必使用所有get_friend_user_details_result.

在单个查询中准确获得您想要的内容可以大大提高速度,并且在许多情况下还可以清理您的代码。

于 2013-07-11T11:09:53.443 回答
0
usort($row_array, function($a, $b)
{
 return ($a['points']<$b['points']) ? 1 : -1;
});
于 2013-07-11T10:34:17.690 回答