我编写了一个函数来从2表中获取所有用户的详细信息。这是代码
//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;
使用此功能我可以获取用户详细信息。但不在订单中。应该对DESC进行排序。
如何为此函数编写单个查询,而不是有3个quires。?
或者,
如何对数组'totalPoints'进行排序?
答案 0 :(得分:1)
这是一个基本的连接查询,将所有三个组合成一个。
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;
这可能不是最优化的查询,但它比三个循环更快。绝对可以玩它。